mirror of
https://github.com/th30d4y/OpenLearnX.git
synced 2026-05-26 19:26:33 +00:00
panel & coding
This commit is contained in:
+394
-57
@@ -6,6 +6,7 @@ import asyncio
|
|||||||
from mongo_service import MongoService
|
from mongo_service import MongoService
|
||||||
from web3_service import Web3Service
|
from web3_service import Web3Service
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
# Load environment variables first
|
# Load environment variables first
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@@ -75,11 +76,23 @@ logging.basicConfig(
|
|||||||
)
|
)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ✅ DEFINE check_docker_availability BEFORE using it
|
||||||
|
def check_docker_availability():
|
||||||
|
"""Check if Docker is available for compiler service"""
|
||||||
|
try:
|
||||||
|
import docker
|
||||||
|
client = docker.from_env()
|
||||||
|
client.ping()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
# Initialize services with error handling
|
# Initialize services with error handling
|
||||||
try:
|
try:
|
||||||
mongo_service = MongoService(app.config['MONGODB_URI'])
|
mongo_service = MongoService(app.config['MONGODB_URI'])
|
||||||
app.config['MONGO_SERVICE'] = mongo_service
|
app.config['MONGO_SERVICE'] = mongo_service
|
||||||
MONGO_SERVICE_AVAILABLE = True
|
MONGO_SERVICE_AVAILABLE = True
|
||||||
|
logger.info("✅ MongoDB service initialized")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Failed to initialize MongoDB service: {e}")
|
logging.error(f"Failed to initialize MongoDB service: {e}")
|
||||||
mongo_service = None
|
mongo_service = None
|
||||||
@@ -92,6 +105,7 @@ try:
|
|||||||
)
|
)
|
||||||
app.config['WEB3_SERVICE'] = web3_service
|
app.config['WEB3_SERVICE'] = web3_service
|
||||||
WEB3_SERVICE_AVAILABLE = True
|
WEB3_SERVICE_AVAILABLE = True
|
||||||
|
logger.info("✅ Web3 service initialized")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Failed to initialize Web3 service: {e}")
|
logging.error(f"Failed to initialize Web3 service: {e}")
|
||||||
web3_service = None
|
web3_service = None
|
||||||
@@ -100,44 +114,229 @@ except Exception as e:
|
|||||||
# Make services available to routes
|
# Make services available to routes
|
||||||
if WALLET_SERVICE_AVAILABLE:
|
if WALLET_SERVICE_AVAILABLE:
|
||||||
app.config['WALLET_SERVICE'] = wallet_service
|
app.config['WALLET_SERVICE'] = wallet_service
|
||||||
|
logger.info("✅ Wallet service available")
|
||||||
|
|
||||||
if COMPILER_SERVICE_AVAILABLE:
|
if COMPILER_SERVICE_AVAILABLE:
|
||||||
app.config['REAL_COMPILER_SERVICE'] = real_compiler_service
|
app.config['REAL_COMPILER_SERVICE'] = real_compiler_service
|
||||||
|
logger.info("✅ Compiler service available")
|
||||||
|
|
||||||
# ✅ DEFINE check_docker_availability BEFORE using it
|
# ✅ ENHANCED: Register all blueprints with better error handling
|
||||||
def check_docker_availability():
|
|
||||||
"""Check if Docker is available for compiler service"""
|
|
||||||
try:
|
|
||||||
import docker
|
|
||||||
client = docker.from_env()
|
|
||||||
client.ping()
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Register all blueprints with error handling
|
|
||||||
blueprints = [
|
blueprints = [
|
||||||
(auth.bp, '/api/auth'),
|
(auth.bp, '/api/auth', 'Authentication'),
|
||||||
(test_flow.bp, '/api/test'),
|
(test_flow.bp, '/api/test', 'Test Flow'),
|
||||||
(certificate.bp, '/api/certificate'),
|
(certificate.bp, '/api/certificate', 'Certificates'),
|
||||||
(dashboard.bp, '/api/dashboard'),
|
(dashboard.bp, '/api/dashboard', 'Dashboard'),
|
||||||
(courses.bp, '/api/courses'),
|
(courses.bp, '/api/courses', 'Courses'),
|
||||||
(quizzes.bp, '/api/quizzes'),
|
(quizzes.bp, '/api/quizzes', 'Quizzes'),
|
||||||
(admin.bp, '/api/admin'),
|
(admin.bp, '/api/admin', 'Admin Panel'),
|
||||||
(exam.bp, '/api/exam'), # Coding exam routes
|
(exam.bp, '/api/exam', 'Coding Exams'), # ✅ Key for coding exam functionality
|
||||||
(compiler.bp, '/api/compiler'), # Compiler routes
|
(compiler.bp, '/api/compiler', 'Code Compiler'), # ✅ Key for compiler functionality
|
||||||
]
|
]
|
||||||
|
|
||||||
for blueprint, url_prefix in blueprints:
|
registered_blueprints = []
|
||||||
|
failed_blueprints = []
|
||||||
|
|
||||||
|
for blueprint, url_prefix, description in blueprints:
|
||||||
try:
|
try:
|
||||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||||
logging.info(f"✅ Registered blueprint: {url_prefix}")
|
registered_blueprints.append((description, url_prefix))
|
||||||
print(f"✅ Registered blueprint: {url_prefix}")
|
logging.info(f"✅ Registered {description}: {url_prefix}")
|
||||||
|
print(f"✅ Registered {description}: {url_prefix}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"❌ Failed to register blueprint {url_prefix}: {e}")
|
failed_blueprints.append((description, url_prefix, str(e)))
|
||||||
print(f"❌ Failed to register blueprint {url_prefix}: {e}")
|
logging.error(f"❌ Failed to register {description} ({url_prefix}): {e}")
|
||||||
|
print(f"❌ Failed to register {description} ({url_prefix}): {e}")
|
||||||
|
|
||||||
# Debug routes
|
# ✅ CRITICAL FIX: Add missing exam info endpoint directly to main.py
|
||||||
|
@app.route('/api/exam/info/<exam_code>', methods=['GET', 'OPTIONS'])
|
||||||
|
def get_exam_info_direct(exam_code):
|
||||||
|
"""Direct exam info endpoint for host panel - CRITICAL FIX"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "GET,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
print(f"📊 DIRECT host panel request for exam: {exam_code}")
|
||||||
|
|
||||||
|
# Get MongoDB connection
|
||||||
|
from pymongo import MongoClient
|
||||||
|
client = MongoClient(app.config['MONGODB_URI'])
|
||||||
|
db = client.openlearnx
|
||||||
|
|
||||||
|
exam = db.exams.find_one({"exam_code": exam_code.upper()})
|
||||||
|
if not exam:
|
||||||
|
print(f"❌ Exam not found: {exam_code}")
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
# Convert datetime to string if needed
|
||||||
|
created_at = exam.get("created_at")
|
||||||
|
if hasattr(created_at, 'isoformat'):
|
||||||
|
created_at = created_at.isoformat()
|
||||||
|
elif created_at:
|
||||||
|
created_at = str(created_at)
|
||||||
|
|
||||||
|
exam_info = {
|
||||||
|
"title": exam.get("title", "Untitled Exam"),
|
||||||
|
"status": exam.get("status", "waiting"),
|
||||||
|
"duration_minutes": exam.get("duration_minutes", 30),
|
||||||
|
"participants_count": len(exam.get("participants", [])),
|
||||||
|
"max_participants": exam.get("max_participants", 50),
|
||||||
|
"problem_title": exam.get("problem", {}).get("title", exam.get("title", "Coding Challenge")),
|
||||||
|
"languages": exam.get("problem", {}).get("languages", ["python"]),
|
||||||
|
"created_at": created_at,
|
||||||
|
"host_name": exam.get("host_name", "Unknown Host")
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"✅ Found exam: {exam_info['title']} (Status: {exam_info['status']})")
|
||||||
|
return jsonify({"success": True, "exam_info": exam_info})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error getting exam info: {str(e)}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return jsonify({"success": False, "error": f"Server error: {str(e)}"}), 500
|
||||||
|
|
||||||
|
# ✅ ADD: Additional missing host panel endpoints
|
||||||
|
@app.route('/api/exam/participants/<exam_code>', methods=['GET', 'OPTIONS'])
|
||||||
|
def get_participants_direct(exam_code):
|
||||||
|
"""Get participants for host panel"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "GET,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
print(f"👥 DIRECT participants request for exam: {exam_code}")
|
||||||
|
|
||||||
|
from pymongo import MongoClient
|
||||||
|
client = MongoClient(app.config['MONGODB_URI'])
|
||||||
|
db = client.openlearnx
|
||||||
|
|
||||||
|
exam = db.exams.find_one({"exam_code": exam_code.upper()})
|
||||||
|
if not exam:
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
participants = exam.get("participants", [])
|
||||||
|
|
||||||
|
# Format participant data
|
||||||
|
formatted_participants = []
|
||||||
|
for participant in participants:
|
||||||
|
# Convert datetime to string if needed
|
||||||
|
joined_at = participant.get("joined_at")
|
||||||
|
if hasattr(joined_at, 'isoformat'):
|
||||||
|
joined_at = joined_at.isoformat()
|
||||||
|
elif joined_at:
|
||||||
|
joined_at = str(joined_at)
|
||||||
|
|
||||||
|
submitted_at = participant.get("submitted_at")
|
||||||
|
if hasattr(submitted_at, 'isoformat'):
|
||||||
|
submitted_at = submitted_at.isoformat()
|
||||||
|
elif submitted_at:
|
||||||
|
submitted_at = str(submitted_at)
|
||||||
|
|
||||||
|
participant_data = {
|
||||||
|
"name": participant.get("name", ""),
|
||||||
|
"score": participant.get("score", 0),
|
||||||
|
"completed": participant.get("completed", False),
|
||||||
|
"joined_at": joined_at,
|
||||||
|
"submitted_at": submitted_at
|
||||||
|
}
|
||||||
|
formatted_participants.append(participant_data)
|
||||||
|
|
||||||
|
print(f"✅ Found {len(formatted_participants)} participants for exam {exam_code}")
|
||||||
|
return jsonify({"success": True, "participants": formatted_participants})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error getting participants: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/exam/remove-participant', methods=['POST', 'OPTIONS'])
|
||||||
|
def remove_participant_direct():
|
||||||
|
"""Remove participant from exam (host panel)"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "POST,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
exam_code = data.get('exam_code', '').upper()
|
||||||
|
participant_name = data.get('participant_name', '')
|
||||||
|
|
||||||
|
print(f"🗑️ DIRECT remove participant request: {participant_name} from {exam_code}")
|
||||||
|
|
||||||
|
if not exam_code or not participant_name:
|
||||||
|
return jsonify({"success": False, "error": "Missing exam_code or participant_name"}), 400
|
||||||
|
|
||||||
|
from pymongo import MongoClient
|
||||||
|
client = MongoClient(app.config['MONGODB_URI'])
|
||||||
|
db = client.openlearnx
|
||||||
|
|
||||||
|
result = db.exams.update_one(
|
||||||
|
{"exam_code": exam_code},
|
||||||
|
{"$pull": {"participants": {"name": participant_name}}}
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.modified_count > 0:
|
||||||
|
print(f"✅ Removed participant {participant_name} from exam {exam_code}")
|
||||||
|
return jsonify({"success": True, "message": f"Participant {participant_name} removed successfully"})
|
||||||
|
else:
|
||||||
|
return jsonify({"success": False, "error": "Participant not found or already removed"}), 404
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error removing participant: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/exam/stop-exam', methods=['POST', 'OPTIONS'])
|
||||||
|
def stop_exam_direct():
|
||||||
|
"""Stop exam (host panel)"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "POST,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
exam_code = data.get('exam_code', '').upper()
|
||||||
|
|
||||||
|
print(f"🛑 DIRECT stop exam request: {exam_code}")
|
||||||
|
|
||||||
|
if not exam_code:
|
||||||
|
return jsonify({"success": False, "error": "Missing exam_code"}), 400
|
||||||
|
|
||||||
|
from pymongo import MongoClient
|
||||||
|
client = MongoClient(app.config['MONGODB_URI'])
|
||||||
|
db = client.openlearnx
|
||||||
|
|
||||||
|
result = db.exams.update_one(
|
||||||
|
{"exam_code": exam_code},
|
||||||
|
{"$set": {
|
||||||
|
"status": "completed",
|
||||||
|
"ended_at": datetime.now().isoformat(),
|
||||||
|
"ended_by": "host"
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.modified_count > 0:
|
||||||
|
print(f"✅ Exam {exam_code} stopped by host")
|
||||||
|
return jsonify({"success": True, "message": "Exam stopped successfully"})
|
||||||
|
else:
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error stopping exam: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
# ✅ ENHANCED: Debug routes with better structure
|
||||||
@app.route('/debug/routes')
|
@app.route('/debug/routes')
|
||||||
def debug_routes():
|
def debug_routes():
|
||||||
"""Debug route to see all registered routes"""
|
"""Debug route to see all registered routes"""
|
||||||
@@ -150,7 +349,15 @@ def debug_routes():
|
|||||||
})
|
})
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"total_routes": len(routes),
|
"total_routes": len(routes),
|
||||||
"routes": sorted(routes, key=lambda x: x['rule'])
|
"routes": sorted(routes, key=lambda x: x['rule']),
|
||||||
|
"registered_blueprints": [desc for desc, url in registered_blueprints],
|
||||||
|
"failed_blueprints": failed_blueprints,
|
||||||
|
"direct_exam_routes_added": [
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam"
|
||||||
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
@app.route('/debug/exam-routes')
|
@app.route('/debug/exam-routes')
|
||||||
@@ -164,9 +371,22 @@ def debug_exam_routes():
|
|||||||
'methods': list(rule.methods),
|
'methods': list(rule.methods),
|
||||||
'rule': str(rule)
|
'rule': str(rule)
|
||||||
})
|
})
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"exam_routes": exam_routes,
|
"exam_routes": exam_routes,
|
||||||
"exam_blueprint_registered": hasattr(exam, 'bp')
|
"exam_blueprint_registered": any('Coding Exams' in desc for desc, _ in registered_blueprints),
|
||||||
|
"expected_exam_routes": [
|
||||||
|
"/api/exam/create-exam",
|
||||||
|
"/api/exam/join-exam",
|
||||||
|
"/api/exam/start-exam",
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam",
|
||||||
|
"/api/exam/leaderboard/<exam_code>",
|
||||||
|
"/api/exam/test"
|
||||||
|
],
|
||||||
|
"direct_routes_added": True
|
||||||
})
|
})
|
||||||
|
|
||||||
@app.route('/debug/services')
|
@app.route('/debug/services')
|
||||||
@@ -181,10 +401,17 @@ def debug_services():
|
|||||||
"docker": check_docker_availability()
|
"docker": check_docker_availability()
|
||||||
},
|
},
|
||||||
"app_config_keys": list(app.config.keys()),
|
"app_config_keys": list(app.config.keys()),
|
||||||
"blueprint_count": len(app.blueprints)
|
"blueprint_count": len(app.blueprints),
|
||||||
|
"registered_blueprints": registered_blueprints,
|
||||||
|
"failed_blueprints": failed_blueprints,
|
||||||
|
"exam_system_ready": all([
|
||||||
|
MONGO_SERVICE_AVAILABLE,
|
||||||
|
any('Coding Exams' in desc for desc, _ in registered_blueprints)
|
||||||
|
]),
|
||||||
|
"direct_exam_endpoints_added": True
|
||||||
})
|
})
|
||||||
|
|
||||||
# Direct exam test route
|
# ✅ ENHANCED: Direct exam test route with better functionality
|
||||||
@app.route('/api/exam/test-direct', methods=['GET', 'POST', 'OPTIONS'])
|
@app.route('/api/exam/test-direct', methods=['GET', 'POST', 'OPTIONS'])
|
||||||
def test_exam_direct():
|
def test_exam_direct():
|
||||||
"""Direct test route for exam functionality"""
|
"""Direct test route for exam functionality"""
|
||||||
@@ -199,22 +426,28 @@ def test_exam_direct():
|
|||||||
"success": True,
|
"success": True,
|
||||||
"message": "Direct exam route is working",
|
"message": "Direct exam route is working",
|
||||||
"method": request.method,
|
"method": request.method,
|
||||||
"timestamp": os.popen('date').read().strip(),
|
"timestamp": datetime.now().isoformat(),
|
||||||
"data": request.json if request.method == "POST" else None
|
"data": request.json if request.method == "POST" else None,
|
||||||
|
"mongo_available": MONGO_SERVICE_AVAILABLE,
|
||||||
|
"exam_blueprint_registered": any('Coding Exams' in desc for desc, _ in registered_blueprints),
|
||||||
|
"direct_endpoints_added": True
|
||||||
})
|
})
|
||||||
|
|
||||||
# Health check endpoints
|
# ✅ ENHANCED: Health check endpoints
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def health_check():
|
def health_check():
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"status": "OpenLearnX API is running",
|
"status": "OpenLearnX API is running",
|
||||||
"version": "2.0.0",
|
"version": "2.0.1",
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
"features": {
|
"features": {
|
||||||
"blockchain": WEB3_SERVICE_AVAILABLE,
|
"blockchain": WEB3_SERVICE_AVAILABLE,
|
||||||
"coding_exams": COMPILER_SERVICE_AVAILABLE,
|
"coding_exams": COMPILER_SERVICE_AVAILABLE,
|
||||||
"wallet_auth": WALLET_SERVICE_AVAILABLE,
|
"wallet_auth": WALLET_SERVICE_AVAILABLE,
|
||||||
"database": MONGO_SERVICE_AVAILABLE,
|
"database": MONGO_SERVICE_AVAILABLE,
|
||||||
"real_compiler": COMPILER_SERVICE_AVAILABLE
|
"real_compiler": COMPILER_SERVICE_AVAILABLE,
|
||||||
|
"docker": check_docker_availability(),
|
||||||
|
"direct_exam_endpoints": True
|
||||||
},
|
},
|
||||||
"endpoints": {
|
"endpoints": {
|
||||||
"auth": "/api/auth",
|
"auth": "/api/auth",
|
||||||
@@ -231,7 +464,10 @@ def health_check():
|
|||||||
"/debug/exam-routes",
|
"/debug/exam-routes",
|
||||||
"/debug/services",
|
"/debug/services",
|
||||||
"/api/exam/test-direct"
|
"/api/exam/test-direct"
|
||||||
]
|
],
|
||||||
|
"registered_blueprints": len(registered_blueprints),
|
||||||
|
"failed_blueprints": len(failed_blueprints),
|
||||||
|
"host_panel_fix": "✅ Direct endpoints added"
|
||||||
})
|
})
|
||||||
|
|
||||||
@app.route('/api/health')
|
@app.route('/api/health')
|
||||||
@@ -239,7 +475,7 @@ def api_health():
|
|||||||
"""Comprehensive API health check"""
|
"""Comprehensive API health check"""
|
||||||
health_status = {
|
health_status = {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"timestamp": os.popen('date').read().strip(),
|
"timestamp": datetime.now().isoformat(),
|
||||||
"services": {
|
"services": {
|
||||||
"mongodb": MONGO_SERVICE_AVAILABLE,
|
"mongodb": MONGO_SERVICE_AVAILABLE,
|
||||||
"web3": WEB3_SERVICE_AVAILABLE,
|
"web3": WEB3_SERVICE_AVAILABLE,
|
||||||
@@ -253,10 +489,24 @@ def api_health():
|
|||||||
"secret_key_set": bool(app.config.get('SECRET_KEY')),
|
"secret_key_set": bool(app.config.get('SECRET_KEY')),
|
||||||
"admin_token_set": bool(app.config.get('ADMIN_TOKEN'))
|
"admin_token_set": bool(app.config.get('ADMIN_TOKEN'))
|
||||||
},
|
},
|
||||||
"blueprints_registered": list(app.blueprints.keys())
|
"blueprints_registered": list(app.blueprints.keys()),
|
||||||
|
"exam_system": {
|
||||||
|
"ready": all([
|
||||||
|
MONGO_SERVICE_AVAILABLE,
|
||||||
|
any('Coding Exams' in desc for desc, _ in registered_blueprints)
|
||||||
|
]),
|
||||||
|
"features": [
|
||||||
|
"Real-time exam creation",
|
||||||
|
"Student joining with exam codes",
|
||||||
|
"Host management panel",
|
||||||
|
"Live leaderboards",
|
||||||
|
"Multi-language compiler support"
|
||||||
|
],
|
||||||
|
"host_panel_fix": "✅ Direct endpoints added to main.py"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Check MongoDB connection
|
# ✅ ENHANCED: Check MongoDB connection
|
||||||
if MONGO_SERVICE_AVAILABLE:
|
if MONGO_SERVICE_AVAILABLE:
|
||||||
try:
|
try:
|
||||||
from pymongo import MongoClient
|
from pymongo import MongoClient
|
||||||
@@ -267,7 +517,7 @@ def api_health():
|
|||||||
health_status["services"]["mongodb_connection"] = f"error: {str(e)}"
|
health_status["services"]["mongodb_connection"] = f"error: {str(e)}"
|
||||||
health_status["status"] = "degraded"
|
health_status["status"] = "degraded"
|
||||||
|
|
||||||
# Check Web3 connection
|
# ✅ ENHANCED: Check Web3 connection
|
||||||
if WEB3_SERVICE_AVAILABLE:
|
if WEB3_SERVICE_AVAILABLE:
|
||||||
try:
|
try:
|
||||||
if web3_service and web3_service.w3.is_connected():
|
if web3_service and web3_service.w3.is_connected():
|
||||||
@@ -287,6 +537,7 @@ def admin_health():
|
|||||||
"""Admin-specific health check"""
|
"""Admin-specific health check"""
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"status": "Admin API is running",
|
"status": "Admin API is running",
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
"admin_token_configured": bool(app.config.get('ADMIN_TOKEN')),
|
"admin_token_configured": bool(app.config.get('ADMIN_TOKEN')),
|
||||||
"admin_endpoints": [
|
"admin_endpoints": [
|
||||||
"/api/admin/dashboard",
|
"/api/admin/dashboard",
|
||||||
@@ -302,7 +553,11 @@ def admin_health():
|
|||||||
"/api/exam/start-exam",
|
"/api/exam/start-exam",
|
||||||
"/api/exam/submit-solution",
|
"/api/exam/submit-solution",
|
||||||
"/api/exam/leaderboard/<exam_code>",
|
"/api/exam/leaderboard/<exam_code>",
|
||||||
"/api/exam/host-dashboard/<exam_code>"
|
"/api/exam/host-dashboard/<exam_code>",
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam"
|
||||||
],
|
],
|
||||||
"compiler_endpoints": [
|
"compiler_endpoints": [
|
||||||
"/api/compiler/languages",
|
"/api/compiler/languages",
|
||||||
@@ -311,15 +566,26 @@ def admin_health():
|
|||||||
"/api/compiler/status/<execution_id>",
|
"/api/compiler/status/<execution_id>",
|
||||||
"/api/compiler/test",
|
"/api/compiler/test",
|
||||||
"/api/compiler/stats"
|
"/api/compiler/stats"
|
||||||
]
|
],
|
||||||
|
"exam_system_status": {
|
||||||
|
"ready": all([
|
||||||
|
MONGO_SERVICE_AVAILABLE,
|
||||||
|
any('Coding Exams' in desc for desc, _ in registered_blueprints)
|
||||||
|
]),
|
||||||
|
"mongo_connected": MONGO_SERVICE_AVAILABLE,
|
||||||
|
"exam_routes_registered": any('Coding Exams' in desc for desc, _ in registered_blueprints),
|
||||||
|
"host_panel_endpoints": "✅ Added directly to main.py"
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
# Error handlers
|
# ✅ ENHANCED: Error handlers with better error information
|
||||||
@app.errorhandler(404)
|
@app.errorhandler(404)
|
||||||
def not_found(error):
|
def not_found(error):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"error": "Endpoint not found",
|
"error": "Endpoint not found",
|
||||||
"message": "The requested API endpoint does not exist",
|
"message": "The requested API endpoint does not exist",
|
||||||
|
"requested_path": request.path,
|
||||||
|
"method": request.method,
|
||||||
"available_endpoints": [
|
"available_endpoints": [
|
||||||
"/api/auth", "/api/courses", "/api/admin",
|
"/api/auth", "/api/courses", "/api/admin",
|
||||||
"/api/exam", "/api/dashboard", "/api/certificate",
|
"/api/exam", "/api/dashboard", "/api/certificate",
|
||||||
@@ -329,6 +595,13 @@ def not_found(error):
|
|||||||
"/debug/routes",
|
"/debug/routes",
|
||||||
"/debug/exam-routes",
|
"/debug/exam-routes",
|
||||||
"/debug/services"
|
"/debug/services"
|
||||||
|
],
|
||||||
|
"exam_specific_endpoints": [
|
||||||
|
"/api/exam/create-exam",
|
||||||
|
"/api/exam/join-exam",
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/test-direct"
|
||||||
]
|
]
|
||||||
}), 404
|
}), 404
|
||||||
|
|
||||||
@@ -337,21 +610,24 @@ def internal_error(error):
|
|||||||
app.logger.error(f"Internal server error: {str(error)}")
|
app.logger.error(f"Internal server error: {str(error)}")
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"error": "Internal server error",
|
"error": "Internal server error",
|
||||||
"message": "An unexpected error occurred on the server"
|
"message": "An unexpected error occurred on the server",
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
}), 500
|
}), 500
|
||||||
|
|
||||||
@app.errorhandler(403)
|
@app.errorhandler(403)
|
||||||
def forbidden(error):
|
def forbidden(error):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"error": "Forbidden",
|
"error": "Forbidden",
|
||||||
"message": "Access denied - check your authentication"
|
"message": "Access denied - check your authentication",
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
}), 403
|
}), 403
|
||||||
|
|
||||||
@app.errorhandler(401)
|
@app.errorhandler(401)
|
||||||
def unauthorized(error):
|
def unauthorized(error):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"error": "Unauthorized",
|
"error": "Unauthorized",
|
||||||
"message": "Authentication required"
|
"message": "Authentication required",
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
}), 401
|
}), 401
|
||||||
|
|
||||||
@app.errorhandler(Exception)
|
@app.errorhandler(Exception)
|
||||||
@@ -359,10 +635,11 @@ def handle_error(error):
|
|||||||
app.logger.error(f"Unhandled error: {str(error)}")
|
app.logger.error(f"Unhandled error: {str(error)}")
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"error": "An unexpected error occurred",
|
"error": "An unexpected error occurred",
|
||||||
"type": type(error).__name__
|
"type": type(error).__name__,
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
}), 500
|
}), 500
|
||||||
|
|
||||||
# Request logging and CORS handling
|
# ✅ ENHANCED: Request logging and CORS handling
|
||||||
@app.before_request
|
@app.before_request
|
||||||
def log_request_info():
|
def log_request_info():
|
||||||
"""Enhanced request logging"""
|
"""Enhanced request logging"""
|
||||||
@@ -374,6 +651,10 @@ def log_request_info():
|
|||||||
logger.info(f"Exam request: {request.method} {request.path}")
|
logger.info(f"Exam request: {request.method} {request.path}")
|
||||||
print(f"📝 Exam request: {request.method} {request.path}")
|
print(f"📝 Exam request: {request.method} {request.path}")
|
||||||
|
|
||||||
|
# Log request data for debugging
|
||||||
|
if request.method in ['POST', 'PUT'] and request.json:
|
||||||
|
print(f"📦 Request data: {request.json}")
|
||||||
|
|
||||||
if '/api/compiler' in request.path:
|
if '/api/compiler' in request.path:
|
||||||
logger.info(f"Compiler request: {request.method} {request.path}")
|
logger.info(f"Compiler request: {request.method} {request.path}")
|
||||||
|
|
||||||
@@ -396,13 +677,34 @@ def after_request(response):
|
|||||||
response.headers.add('X-XSS-Protection', '1; mode=block')
|
response.headers.add('X-XSS-Protection', '1; mode=block')
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# Startup function
|
# ✅ ENHANCED: Startup function with comprehensive initialization
|
||||||
def initialize_application():
|
def initialize_application():
|
||||||
"""Initialize application with comprehensive error handling"""
|
"""Initialize application with comprehensive error handling"""
|
||||||
try:
|
try:
|
||||||
logger.info("🚀 Initializing OpenLearnX Backend...")
|
logger.info("🚀 Initializing OpenLearnX Backend...")
|
||||||
print("🚀 Initializing OpenLearnX Backend...")
|
print("🚀 Initializing OpenLearnX Backend...")
|
||||||
|
|
||||||
|
# ✅ Enhanced blueprint registration status
|
||||||
|
print(f"📋 Blueprint Registration Status:")
|
||||||
|
for description, url_prefix in registered_blueprints:
|
||||||
|
print(f" ✅ {description}: {url_prefix}")
|
||||||
|
|
||||||
|
if failed_blueprints:
|
||||||
|
print(f"❌ Failed Blueprints:")
|
||||||
|
for description, url_prefix, error in failed_blueprints:
|
||||||
|
print(f" ❌ {description}: {url_prefix} - {error}")
|
||||||
|
|
||||||
|
# ✅ Show direct endpoints added
|
||||||
|
print(f"🔧 Direct Exam Endpoints Added to main.py:")
|
||||||
|
direct_endpoints = [
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam"
|
||||||
|
]
|
||||||
|
for endpoint in direct_endpoints:
|
||||||
|
print(f" ✅ {endpoint}")
|
||||||
|
|
||||||
# Test MongoDB connection
|
# Test MongoDB connection
|
||||||
if MONGO_SERVICE_AVAILABLE:
|
if MONGO_SERVICE_AVAILABLE:
|
||||||
try:
|
try:
|
||||||
@@ -447,7 +749,7 @@ def initialize_application():
|
|||||||
logger.warning(f"⚠️ Docker connection error: {e}")
|
logger.warning(f"⚠️ Docker connection error: {e}")
|
||||||
print(f"⚠️ Docker connection error: {e}")
|
print(f"⚠️ Docker connection error: {e}")
|
||||||
|
|
||||||
# Log configuration
|
# ✅ Enhanced configuration summary
|
||||||
logger.info("📋 Configuration Summary:")
|
logger.info("📋 Configuration Summary:")
|
||||||
print("📋 Configuration Summary:")
|
print("📋 Configuration Summary:")
|
||||||
config_items = [
|
config_items = [
|
||||||
@@ -455,7 +757,9 @@ def initialize_application():
|
|||||||
("Blockchain", WEB3_SERVICE_AVAILABLE),
|
("Blockchain", WEB3_SERVICE_AVAILABLE),
|
||||||
("Wallet Service", WALLET_SERVICE_AVAILABLE),
|
("Wallet Service", WALLET_SERVICE_AVAILABLE),
|
||||||
("Compiler Service", COMPILER_SERVICE_AVAILABLE),
|
("Compiler Service", COMPILER_SERVICE_AVAILABLE),
|
||||||
("Docker", check_docker_availability())
|
("Docker", check_docker_availability()),
|
||||||
|
("Exam System", any('Coding Exams' in desc for desc, _ in registered_blueprints)),
|
||||||
|
("Host Panel Fix", True)
|
||||||
]
|
]
|
||||||
|
|
||||||
for name, available in config_items:
|
for name, available in config_items:
|
||||||
@@ -463,12 +767,13 @@ def initialize_application():
|
|||||||
logger.info(f" • {name}: {status}")
|
logger.info(f" • {name}: {status}")
|
||||||
print(f" • {name}: {status}")
|
print(f" • {name}: {status}")
|
||||||
|
|
||||||
# Log access URLs
|
# ✅ Enhanced access URLs
|
||||||
logger.info("🌐 Access URLs:")
|
logger.info("🌐 Access URLs:")
|
||||||
print("🌐 Access URLs:")
|
print("🌐 Access URLs:")
|
||||||
|
|
||||||
urls = [
|
urls = [
|
||||||
("API Health", "http://127.0.0.1:5000/api/health"),
|
("API Health", "http://127.0.0.1:5000/api/health"),
|
||||||
|
("Main Page", "http://127.0.0.1:5000/"),
|
||||||
("Admin Panel", "http://localhost:3000/admin/login"),
|
("Admin Panel", "http://localhost:3000/admin/login"),
|
||||||
("Coding Exams", "http://localhost:3000/coding"),
|
("Coding Exams", "http://localhost:3000/coding"),
|
||||||
("Real Compiler", "http://localhost:3000/compiler"),
|
("Real Compiler", "http://localhost:3000/compiler"),
|
||||||
@@ -480,18 +785,43 @@ def initialize_application():
|
|||||||
logger.info(f" • {name}: {url}")
|
logger.info(f" • {name}: {url}")
|
||||||
print(f" • {name}: {url}")
|
print(f" • {name}: {url}")
|
||||||
|
|
||||||
# Debug URLs
|
# ✅ Enhanced debug URLs
|
||||||
print("🔧 Debug URLs:")
|
print("🔧 Debug URLs:")
|
||||||
debug_urls = [
|
debug_urls = [
|
||||||
("All Routes", "http://127.0.0.1:5000/debug/routes"),
|
("All Routes", "http://127.0.0.1:5000/debug/routes"),
|
||||||
("Exam Routes", "http://127.0.0.1:5000/debug/exam-routes"),
|
("Exam Routes", "http://127.0.0.1:5000/debug/exam-routes"),
|
||||||
("Services", "http://127.0.0.1:5000/debug/services"),
|
("Services", "http://127.0.0.1:5000/debug/services"),
|
||||||
("Direct Test", "http://127.0.0.1:5000/api/exam/test-direct")
|
("Direct Test", "http://127.0.0.1:5000/api/exam/test-direct"),
|
||||||
|
("Admin Health", "http://127.0.0.1:5000/api/admin/health"),
|
||||||
|
("Exam Info Test", "http://127.0.0.1:5000/api/exam/info/TEST123")
|
||||||
]
|
]
|
||||||
|
|
||||||
for name, url in debug_urls:
|
for name, url in debug_urls:
|
||||||
print(f" • {name}: {url}")
|
print(f" • {name}: {url}")
|
||||||
|
|
||||||
|
# ✅ Enhanced exam system status
|
||||||
|
exam_ready = all([
|
||||||
|
MONGO_SERVICE_AVAILABLE,
|
||||||
|
any('Coding Exams' in desc for desc, _ in registered_blueprints)
|
||||||
|
])
|
||||||
|
|
||||||
|
print(f"📝 Exam System Status: {'✅ Ready' if exam_ready else '❌ Not Ready'}")
|
||||||
|
print(f"🔧 Host Panel Fix: ✅ Direct endpoints added to main.py")
|
||||||
|
|
||||||
|
if exam_ready:
|
||||||
|
print("📝 Exam Features Available:")
|
||||||
|
features = [
|
||||||
|
"Create coding exams with 6-character codes",
|
||||||
|
"Students join with exam codes",
|
||||||
|
"Host management panel with live updates",
|
||||||
|
"Real-time participant monitoring",
|
||||||
|
"Live leaderboards with scoring",
|
||||||
|
"Multi-language code execution",
|
||||||
|
"Host panel endpoints working directly"
|
||||||
|
]
|
||||||
|
for feature in features:
|
||||||
|
print(f" • {feature}")
|
||||||
|
|
||||||
# Log compiler features
|
# Log compiler features
|
||||||
if COMPILER_SERVICE_AVAILABLE:
|
if COMPILER_SERVICE_AVAILABLE:
|
||||||
logger.info("💻 Compiler Features:")
|
logger.info("💻 Compiler Features:")
|
||||||
@@ -507,7 +837,7 @@ def initialize_application():
|
|||||||
logger.info(f" • {feature}")
|
logger.info(f" • {feature}")
|
||||||
print(f" • {feature}")
|
print(f" • {feature}")
|
||||||
|
|
||||||
# Log admin token (partially masked)
|
# ✅ Enhanced admin token logging
|
||||||
admin_token = app.config.get('ADMIN_TOKEN', 'admin-secret-key')
|
admin_token = app.config.get('ADMIN_TOKEN', 'admin-secret-key')
|
||||||
if admin_token:
|
if admin_token:
|
||||||
logger.info(f"🔑 Admin token configured: {admin_token[:8]}...")
|
logger.info(f"🔑 Admin token configured: {admin_token[:8]}...")
|
||||||
@@ -536,13 +866,20 @@ if __name__ == '__main__':
|
|||||||
logger.info("📚 Features: Blockchain Certificates, Coding Exams, Wallet Auth, Real Multi-language Compiler")
|
logger.info("📚 Features: Blockchain Certificates, Coding Exams, Wallet Auth, Real Multi-language Compiler")
|
||||||
print("📚 Features: Blockchain Certificates, Coding Exams, Wallet Auth, Real Multi-language Compiler")
|
print("📚 Features: Blockchain Certificates, Coding Exams, Wallet Auth, Real Multi-language Compiler")
|
||||||
|
|
||||||
|
# ✅ Enhanced server info
|
||||||
|
print(f"🌐 Server will be available at:")
|
||||||
|
print(f" • Local: http://127.0.0.1:5000")
|
||||||
|
print(f" • Network: http://0.0.0.0:5000")
|
||||||
|
print(f"📱 Frontend should connect to: http://127.0.0.1:5000")
|
||||||
|
print(f"🔧 Host Panel Fix: ✅ Direct endpoints added for exam info")
|
||||||
|
|
||||||
# Start Flask application
|
# Start Flask application
|
||||||
app.run(
|
app.run(
|
||||||
debug=True,
|
debug=True,
|
||||||
host='0.0.0.0',
|
host='0.0.0.0',
|
||||||
port=5000,
|
port=5000,
|
||||||
threaded=True,
|
threaded=True,
|
||||||
use_reloader=False
|
use_reloader=False # Prevent double initialization
|
||||||
)
|
)
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
@@ -458,6 +458,146 @@ def get_host_dashboard(exam_code):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"error": str(e)}), 500
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
|
# ✅ CORRECTED: Host panel management endpoints (using Blueprint decorators)
|
||||||
|
@bp.route('/info/<exam_code>', methods=['GET', 'OPTIONS'])
|
||||||
|
def get_exam_info(exam_code):
|
||||||
|
"""Get detailed information about an exam for the host panel"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "GET,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
exam = db.exams.find_one({"exam_code": exam_code.upper()})
|
||||||
|
if not exam:
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
exam_info = {
|
||||||
|
"title": exam["title"],
|
||||||
|
"status": exam["status"],
|
||||||
|
"duration_minutes": exam["duration_minutes"],
|
||||||
|
"participants_count": len(exam.get("participants", [])),
|
||||||
|
"max_participants": exam["max_participants"],
|
||||||
|
"problem_title": exam.get("problem", {}).get("title", exam["title"]),
|
||||||
|
"languages": exam.get("problem", {}).get("languages", ["python"]),
|
||||||
|
"created_at": exam["created_at"],
|
||||||
|
"host_name": exam["host_name"]
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"📊 Host panel requested info for exam {exam_code}")
|
||||||
|
return jsonify({"success": True, "exam_info": exam_info})
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error getting exam info: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
@bp.route('/participants/<exam_code>', methods=['GET', 'OPTIONS'])
|
||||||
|
def get_participants(exam_code):
|
||||||
|
"""Get list of participants for host panel monitoring"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "GET,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
exam = db.exams.find_one({"exam_code": exam_code.upper()})
|
||||||
|
if not exam:
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
participants = exam.get("participants", [])
|
||||||
|
|
||||||
|
# Format participant data for host panel
|
||||||
|
formatted_participants = []
|
||||||
|
for participant in participants:
|
||||||
|
participant_data = {
|
||||||
|
"name": participant.get("name", ""),
|
||||||
|
"score": participant.get("score", 0),
|
||||||
|
"completed": participant.get("completed", False),
|
||||||
|
"joined_at": participant.get("joined_at", ""),
|
||||||
|
"submitted_at": participant.get("submitted_at", None)
|
||||||
|
}
|
||||||
|
formatted_participants.append(participant_data)
|
||||||
|
|
||||||
|
print(f"👥 Retrieved {len(formatted_participants)} participants for exam {exam_code}")
|
||||||
|
return jsonify({"success": True, "participants": formatted_participants})
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error getting participants: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
@bp.route('/remove-participant', methods=['POST', 'OPTIONS'])
|
||||||
|
def remove_participant():
|
||||||
|
"""Remove a participant from an exam (host only)"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "POST,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
exam_code = data.get('exam_code', '').upper()
|
||||||
|
participant_name = data.get('participant_name', '')
|
||||||
|
|
||||||
|
if not exam_code or not participant_name:
|
||||||
|
return jsonify({"success": False, "error": "Missing exam_code or participant_name"}), 400
|
||||||
|
|
||||||
|
# Remove participant from exam
|
||||||
|
result = db.exams.update_one(
|
||||||
|
{"exam_code": exam_code},
|
||||||
|
{"$pull": {"participants": {"name": participant_name}}}
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.modified_count > 0:
|
||||||
|
print(f"🗑️ Host removed participant {participant_name} from exam {exam_code}")
|
||||||
|
return jsonify({"success": True, "message": f"Participant {participant_name} removed successfully"})
|
||||||
|
else:
|
||||||
|
return jsonify({"success": False, "error": "Participant not found or already removed"}), 404
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error removing participant: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
|
@bp.route('/stop-exam', methods=['POST', 'OPTIONS'])
|
||||||
|
def stop_exam():
|
||||||
|
"""Stop an exam early (host only)"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "POST,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
exam_code = data.get('exam_code', '').upper()
|
||||||
|
|
||||||
|
if not exam_code:
|
||||||
|
return jsonify({"success": False, "error": "Missing exam_code"}), 400
|
||||||
|
|
||||||
|
# Update exam status to completed
|
||||||
|
result = db.exams.update_one(
|
||||||
|
{"exam_code": exam_code},
|
||||||
|
{"$set": {
|
||||||
|
"status": "completed",
|
||||||
|
"ended_at": datetime.now().isoformat(),
|
||||||
|
"ended_by": "host"
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.modified_count > 0:
|
||||||
|
print(f"🛑 Exam {exam_code} stopped early by host")
|
||||||
|
return jsonify({"success": True, "message": "Exam stopped successfully"})
|
||||||
|
else:
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error stopping exam: {str(e)}")
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|
||||||
@bp.route("/debug-join-data", methods=["POST", "OPTIONS"])
|
@bp.route("/debug-join-data", methods=["POST", "OPTIONS"])
|
||||||
def debug_join_data():
|
def debug_join_data():
|
||||||
"""Debug what data is actually being received"""
|
"""Debug what data is actually being received"""
|
||||||
@@ -493,6 +633,10 @@ def test_exam_route():
|
|||||||
"/api/exam/leaderboard/<exam_code>",
|
"/api/exam/leaderboard/<exam_code>",
|
||||||
"/api/exam/get-problem/<exam_code>",
|
"/api/exam/get-problem/<exam_code>",
|
||||||
"/api/exam/host-dashboard/<exam_code>",
|
"/api/exam/host-dashboard/<exam_code>",
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam",
|
||||||
"/api/exam/debug-join-data"
|
"/api/exam/debug-join-data"
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
@@ -509,7 +653,54 @@ def exam_root():
|
|||||||
"/api/exam/leaderboard/<exam_code>",
|
"/api/exam/leaderboard/<exam_code>",
|
||||||
"/api/exam/get-problem/<exam_code>",
|
"/api/exam/get-problem/<exam_code>",
|
||||||
"/api/exam/host-dashboard/<exam_code>",
|
"/api/exam/host-dashboard/<exam_code>",
|
||||||
|
"/api/exam/info/<exam_code>",
|
||||||
|
"/api/exam/participants/<exam_code>",
|
||||||
|
"/api/exam/remove-participant",
|
||||||
|
"/api/exam/stop-exam",
|
||||||
"/api/exam/test",
|
"/api/exam/test",
|
||||||
"/api/exam/debug-join-data"
|
"/api/exam/debug-join-data"
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
@bp.route('/info/<exam_code>', methods=['GET', 'OPTIONS'])
|
||||||
|
def get_exam_info(exam_code):
|
||||||
|
"""Get detailed information about an exam for the host panel"""
|
||||||
|
if request.method == "OPTIONS":
|
||||||
|
response = jsonify({'status': 'ok'})
|
||||||
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
||||||
|
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||||
|
response.headers.add("Access-Control-Allow-Methods", "GET,OPTIONS")
|
||||||
|
return response
|
||||||
|
|
||||||
|
try:
|
||||||
|
print(f"📊 Host panel requesting info for exam: {exam_code}")
|
||||||
|
|
||||||
|
exam = db.exams.find_one({"exam_code": exam_code.upper()})
|
||||||
|
if not exam:
|
||||||
|
print(f"❌ Exam not found: {exam_code}")
|
||||||
|
return jsonify({"success": False, "error": "Exam not found"}), 404
|
||||||
|
|
||||||
|
# Convert datetime objects to strings for JSON serialization
|
||||||
|
created_at = exam.get("created_at")
|
||||||
|
if hasattr(created_at, 'isoformat'):
|
||||||
|
created_at = created_at.isoformat()
|
||||||
|
|
||||||
|
exam_info = {
|
||||||
|
"title": exam["title"],
|
||||||
|
"status": exam["status"],
|
||||||
|
"duration_minutes": exam["duration_minutes"],
|
||||||
|
"participants_count": len(exam.get("participants", [])),
|
||||||
|
"max_participants": exam.get("max_participants", 50),
|
||||||
|
"problem_title": exam.get("problem", {}).get("title", exam["title"]),
|
||||||
|
"languages": exam.get("problem", {}).get("languages", ["python"]),
|
||||||
|
"created_at": created_at,
|
||||||
|
"host_name": exam["host_name"]
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"✅ Found exam: {exam['title']} (Status: {exam['status']})")
|
||||||
|
return jsonify({"success": True, "exam_info": exam_info})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error getting exam info: {str(e)}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return jsonify({"success": False, "error": str(e)}), 500
|
||||||
|
|||||||
@@ -1,87 +1,114 @@
|
|||||||
'use client'
|
'use client'
|
||||||
import React, { useState, useEffect } from 'react'
|
import React, { useState, useEffect } from 'react'
|
||||||
import { useParams, useRouter } from 'next/navigation'
|
import { useRouter, useParams } from 'next/navigation'
|
||||||
import {
|
import {
|
||||||
Users, Trophy, Clock, Play, Square, UserX, AlertTriangle,
|
Users,
|
||||||
RefreshCw, Settings, BarChart, Eye, Trash2, Plus, Timer
|
Trophy,
|
||||||
|
Clock,
|
||||||
|
Play,
|
||||||
|
Pause,
|
||||||
|
Square,
|
||||||
|
UserMinus,
|
||||||
|
RefreshCw,
|
||||||
|
Settings,
|
||||||
|
Monitor,
|
||||||
|
AlertCircle
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
|
||||||
interface Participant {
|
interface Participant {
|
||||||
name: string
|
name: string
|
||||||
joined_at: string
|
|
||||||
score: number
|
score: number
|
||||||
completed: boolean
|
completed: boolean
|
||||||
language?: string
|
submitted_at?: string
|
||||||
submission_time?: string
|
joined_at: string
|
||||||
rank?: number
|
|
||||||
kicked?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ExamData {
|
interface ExamInfo {
|
||||||
exam_info: {
|
|
||||||
exam_code: string
|
|
||||||
title: string
|
title: string
|
||||||
status: string
|
status: 'waiting' | 'active' | 'completed'
|
||||||
duration_minutes: number
|
duration_minutes: number
|
||||||
|
participants_count: number
|
||||||
max_participants: number
|
max_participants: number
|
||||||
time_elapsed: number
|
problem_title: string
|
||||||
time_remaining: number
|
languages: string[]
|
||||||
start_time?: string
|
created_at: string
|
||||||
end_time?: string
|
host_name: string
|
||||||
}
|
|
||||||
participants: {
|
|
||||||
total: number
|
|
||||||
completed: number
|
|
||||||
working: number
|
|
||||||
all_participants: Participant[]
|
|
||||||
recent_joins: Participant[]
|
|
||||||
}
|
|
||||||
leaderboard: Participant[]
|
|
||||||
statistics: {
|
|
||||||
average_score: number
|
|
||||||
highest_score: number
|
|
||||||
lowest_score: number
|
|
||||||
completion_rate: number
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function HostDashboard() {
|
export default function HostPanel() {
|
||||||
const params = useParams()
|
const params = useParams()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const examCode = params.examCode as string
|
const examCode = params.examCode as string
|
||||||
|
|
||||||
const [examData, setExamData] = useState<ExamData | null>(null)
|
const [examInfo, setExamInfo] = useState<ExamInfo | null>(null)
|
||||||
|
const [participants, setParticipants] = useState<Participant[]>([])
|
||||||
|
const [leaderboard, setLeaderboard] = useState<Participant[]>([])
|
||||||
|
const [timeRemaining, setTimeRemaining] = useState(0)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [activeTab, setActiveTab] = useState<'overview' | 'participants' | 'leaderboard' | 'settings'>('overview')
|
const [error, setError] = useState('')
|
||||||
const [selectedParticipant, setSelectedParticipant] = useState<string | null>(null)
|
|
||||||
const [showKickModal, setShowKickModal] = useState(false)
|
|
||||||
const [refreshInterval, setRefreshInterval] = useState(3000) // 3 seconds
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!examCode) return
|
if (examCode) {
|
||||||
|
fetchExamInfo()
|
||||||
|
fetchParticipants()
|
||||||
|
fetchLeaderboard()
|
||||||
|
|
||||||
|
// Auto-refresh every 5 seconds
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
fetchParticipants()
|
||||||
|
fetchLeaderboard()
|
||||||
|
}, 5000)
|
||||||
|
|
||||||
fetchDashboardData()
|
|
||||||
const interval = setInterval(fetchDashboardData, refreshInterval)
|
|
||||||
return () => clearInterval(interval)
|
return () => clearInterval(interval)
|
||||||
}, [examCode, refreshInterval])
|
}
|
||||||
|
}, [examCode])
|
||||||
|
|
||||||
const fetchDashboardData = async () => {
|
const fetchExamInfo = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`http://127.0.0.1:5000/api/exam/host-dashboard/${examCode}`)
|
const response = await fetch(`http://127.0.0.1:5000/api/exam/info/${examCode}`)
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setExamData(data)
|
setExamInfo(data.exam_info)
|
||||||
|
if (data.exam_info.status === 'active') {
|
||||||
|
startTimer(data.exam_info.duration_minutes * 60)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
console.error('Failed to fetch dashboard data:', data.error)
|
setError('Failed to load exam information')
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching dashboard data:', error)
|
setError('Network error')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fetchParticipants = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`http://127.0.0.1:5000/api/exam/participants/${examCode}`)
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
setParticipants(data.participants)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch participants')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchLeaderboard = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`http://127.0.0.1:5000/api/exam/leaderboard/${examCode}`)
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
setLeaderboard(data.leaderboard)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch leaderboard')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const startExam = async () => {
|
const startExam = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/exam/start-exam', {
|
const response = await fetch('http://127.0.0.1:5000/api/exam/start-exam', {
|
||||||
@@ -92,21 +119,20 @@ export default function HostDashboard() {
|
|||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert('Exam started successfully!')
|
setExamInfo(prev => prev ? { ...prev, status: 'active' } : null)
|
||||||
fetchDashboardData()
|
startTimer(examInfo?.duration_minutes ? examInfo.duration_minutes * 60 : 1800)
|
||||||
|
alert('✅ Exam started! Participants can now begin coding.')
|
||||||
} else {
|
} else {
|
||||||
alert(`Failed to start exam: ${data.error}`)
|
alert(`❌ Failed to start exam: ${data.error}`)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Failed to start exam')
|
alert('❌ Network error occurred')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const endExam = async () => {
|
const stopExam = async () => {
|
||||||
if (!confirm('Are you sure you want to end the exam? This cannot be undone.')) return
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/exam/end-exam', {
|
const response = await fetch('http://127.0.0.1:5000/api/exam/stop-exam', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ exam_code: examCode })
|
body: JSON.stringify({ exam_code: examCode })
|
||||||
@@ -114,41 +140,21 @@ export default function HostDashboard() {
|
|||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert('Exam ended successfully!')
|
setExamInfo(prev => prev ? { ...prev, status: 'completed' } : null)
|
||||||
fetchDashboardData()
|
setTimeRemaining(0)
|
||||||
|
alert('🛑 Exam stopped successfully!')
|
||||||
} else {
|
} else {
|
||||||
alert(`Failed to end exam: ${data.error}`)
|
alert(`❌ Failed to stop exam: ${data.error}`)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Failed to end exam')
|
alert('❌ Network error occurred')
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const extendExam = async (minutes: number) => {
|
|
||||||
try {
|
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/exam/extend-exam', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
exam_code: examCode,
|
|
||||||
additional_minutes: minutes
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
if (data.success) {
|
|
||||||
alert(`Exam extended by ${minutes} minutes!`)
|
|
||||||
fetchDashboardData()
|
|
||||||
} else {
|
|
||||||
alert(`Failed to extend exam: ${data.error}`)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
alert('Failed to extend exam')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeParticipant = async (participantName: string) => {
|
const removeParticipant = async (participantName: string) => {
|
||||||
if (!confirm(`Are you sure you want to remove "${participantName}" from the exam?`)) return
|
if (!confirm(`Are you sure you want to remove "${participantName}" from the exam?`)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/exam/remove-participant', {
|
const response = await fetch('http://127.0.0.1:5000/api/exam/remove-participant', {
|
||||||
@@ -162,18 +168,33 @@ export default function HostDashboard() {
|
|||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert(`Participant "${participantName}" removed successfully!`)
|
alert(`✅ Removed "${participantName}" from the exam`)
|
||||||
fetchDashboardData()
|
fetchParticipants()
|
||||||
setShowKickModal(false)
|
fetchLeaderboard()
|
||||||
setSelectedParticipant(null)
|
|
||||||
} else {
|
} else {
|
||||||
alert(`Failed to remove participant: ${data.error}`)
|
alert(`❌ Failed to remove participant: ${data.error}`)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Failed to remove participant')
|
alert('❌ Network error occurred')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const startTimer = (seconds: number) => {
|
||||||
|
setTimeRemaining(seconds)
|
||||||
|
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
setTimeRemaining(prev => {
|
||||||
|
if (prev <= 1) {
|
||||||
|
clearInterval(timer)
|
||||||
|
alert('⏰ Time is up! Exam has ended.')
|
||||||
|
setExamInfo(prev => prev ? { ...prev, status: 'completed' } : null)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return prev - 1
|
||||||
|
})
|
||||||
|
}, 1000)
|
||||||
|
}
|
||||||
|
|
||||||
const formatTime = (seconds: number) => {
|
const formatTime = (seconds: number) => {
|
||||||
const mins = Math.floor(seconds / 60)
|
const mins = Math.floor(seconds / 60)
|
||||||
const secs = seconds % 60
|
const secs = seconds % 60
|
||||||
@@ -182,10 +203,10 @@ export default function HostDashboard() {
|
|||||||
|
|
||||||
const getStatusColor = (status: string) => {
|
const getStatusColor = (status: string) => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'waiting': return 'bg-yellow-100 text-yellow-800'
|
case 'waiting': return 'bg-yellow-600'
|
||||||
case 'active': return 'bg-green-100 text-green-800'
|
case 'active': return 'bg-green-600'
|
||||||
case 'completed': return 'bg-gray-100 text-gray-800'
|
case 'completed': return 'bg-red-600'
|
||||||
default: return 'bg-gray-100 text-gray-800'
|
default: return 'bg-gray-600'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,25 +214,25 @@ export default function HostDashboard() {
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
|
<div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
|
<RefreshCw className="h-8 w-8 animate-spin mx-auto mb-4" />
|
||||||
<p className="mt-2 text-gray-400">Loading host dashboard...</p>
|
<p>Loading host panel...</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!examData) {
|
if (error || !examInfo) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
|
<div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<AlertTriangle className="h-12 w-12 text-red-400 mx-auto mb-4" />
|
<AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
|
||||||
<h2 className="text-xl font-bold mb-2">Exam Not Found</h2>
|
<h1 className="text-2xl font-bold mb-2">Error</h1>
|
||||||
<p className="text-gray-400">The exam code "{examCode}" is invalid or expired.</p>
|
<p className="text-gray-400 mb-4">{error || 'Exam not found'}</p>
|
||||||
<button
|
<button
|
||||||
onClick={() => router.push('/coding/create')}
|
onClick={() => router.push('/coding')}
|
||||||
className="mt-4 bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded"
|
className="bg-blue-600 hover:bg-blue-700 px-6 py-2 rounded"
|
||||||
>
|
>
|
||||||
Create New Exam
|
Back to Home
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -221,377 +242,247 @@ export default function HostDashboard() {
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white">
|
<div className="min-h-screen bg-gray-900 text-white">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="bg-gray-800 border-b border-gray-700 p-6">
|
<div className="bg-gray-800 border-b border-gray-700 p-4">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold">{examData.exam_info.title}</h1>
|
<h1 className="text-2xl font-bold flex items-center space-x-2">
|
||||||
<div className="flex items-center space-x-4 mt-2">
|
<Monitor className="h-6 w-6" />
|
||||||
<span className="text-lg font-mono font-bold text-blue-400">
|
<span>Host Panel</span>
|
||||||
CODE: {examData.exam_info.exam_code}
|
</h1>
|
||||||
</span>
|
<p className="text-gray-400">Managing exam: {examCode}</p>
|
||||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(examData.exam_info.status)}`}>
|
|
||||||
{examData.exam_info.status.toUpperCase()}
|
|
||||||
</span>
|
|
||||||
<span className="text-gray-400">
|
|
||||||
{examData.participants.total}/{examData.exam_info.max_participants} participants
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center space-x-4">
|
<div className="flex items-center space-x-4">
|
||||||
{/* Timer */}
|
<div className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(examInfo.status)}`}>
|
||||||
{examData.exam_info.status === 'active' && examData.exam_info.time_remaining > 0 && (
|
{examInfo.status.toUpperCase()}
|
||||||
<div className="flex items-center space-x-2 bg-red-900 px-4 py-2 rounded-lg">
|
</div>
|
||||||
<Clock className="h-5 w-5 text-red-400" />
|
|
||||||
<span className="font-mono text-lg">{formatTime(examData.exam_info.time_remaining)}</span>
|
{timeRemaining > 0 && (
|
||||||
|
<div className="flex items-center space-x-2 bg-gray-700 px-3 py-1 rounded">
|
||||||
|
<Clock className="h-4 w-4" />
|
||||||
|
<span className="font-mono text-lg">{formatTime(timeRemaining)}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Control Buttons */}
|
<div className="flex">
|
||||||
{examData.exam_info.status === 'waiting' && (
|
{/* Main Content */}
|
||||||
|
<div className="flex-1 p-6">
|
||||||
|
{/* Exam Info Cards */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Users className="h-8 w-8 text-blue-400" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-400">Participants</p>
|
||||||
|
<p className="text-2xl font-bold">{examInfo.participants_count}/{examInfo.max_participants}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Clock className="h-8 w-8 text-green-400" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-400">Duration</p>
|
||||||
|
<p className="text-2xl font-bold">{examInfo.duration_minutes}m</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Trophy className="h-8 w-8 text-yellow-400" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-400">Completed</p>
|
||||||
|
<p className="text-2xl font-bold">{leaderboard.filter(p => p.completed).length}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Settings className="h-8 w-8 text-purple-400" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-400">Problem</p>
|
||||||
|
<p className="text-lg font-bold">{examInfo.problem_title}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Control Panel */}
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6 mb-8">
|
||||||
|
<h2 className="text-xl font-bold mb-4">Exam Controls</h2>
|
||||||
|
|
||||||
|
<div className="flex space-x-4">
|
||||||
|
{examInfo.status === 'waiting' && (
|
||||||
<button
|
<button
|
||||||
onClick={startExam}
|
onClick={startExam}
|
||||||
className="bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg flex items-center space-x-2"
|
className="bg-green-600 hover:bg-green-700 px-6 py-2 rounded flex items-center space-x-2"
|
||||||
>
|
>
|
||||||
<Play className="h-4 w-4" />
|
<Play className="h-4 w-4" />
|
||||||
<span>Start Exam</span>
|
<span>Start Exam</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{examData.exam_info.status === 'active' && (
|
{examInfo.status === 'active' && (
|
||||||
<div className="flex space-x-2">
|
<>
|
||||||
<button
|
<button
|
||||||
onClick={() => extendExam(10)}
|
onClick={stopExam}
|
||||||
className="bg-yellow-600 hover:bg-yellow-700 px-3 py-2 rounded flex items-center space-x-1"
|
className="bg-red-600 hover:bg-red-700 px-6 py-2 rounded flex items-center space-x-2"
|
||||||
>
|
|
||||||
<Timer className="h-4 w-4" />
|
|
||||||
<span>+10min</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={endExam}
|
|
||||||
className="bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg flex items-center space-x-2"
|
|
||||||
>
|
>
|
||||||
<Square className="h-4 w-4" />
|
<Square className="h-4 w-4" />
|
||||||
<span>End Exam</span>
|
<span>Stop Exam</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={fetchDashboardData}
|
onClick={() => {
|
||||||
className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded"
|
fetchParticipants()
|
||||||
title="Refresh"
|
fetchLeaderboard()
|
||||||
|
}}
|
||||||
|
className="bg-blue-600 hover:bg-blue-700 px-6 py-2 rounded flex items-center space-x-2"
|
||||||
>
|
>
|
||||||
<RefreshCw className="h-4 w-4" />
|
<RefreshCw className="h-4 w-4" />
|
||||||
|
<span>Refresh Data</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="max-w-7xl mx-auto p-6">
|
|
||||||
{/* Tab Navigation */}
|
|
||||||
<div className="flex space-x-1 mb-6">
|
|
||||||
{[
|
|
||||||
{ id: 'overview', label: 'Overview', icon: BarChart },
|
|
||||||
{ id: 'participants', label: 'Participants', icon: Users },
|
|
||||||
{ id: 'leaderboard', label: 'Leaderboard', icon: Trophy },
|
|
||||||
{ id: 'settings', label: 'Settings', icon: Settings }
|
|
||||||
].map(tab => (
|
|
||||||
<button
|
<button
|
||||||
key={tab.id}
|
onClick={() => {
|
||||||
onClick={() => setActiveTab(tab.id as any)}
|
navigator.clipboard.writeText(examCode)
|
||||||
className={`px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors ${
|
alert('Exam code copied to clipboard!')
|
||||||
activeTab === tab.id
|
}}
|
||||||
? 'bg-blue-600 text-white'
|
className="bg-purple-600 hover:bg-purple-700 px-6 py-2 rounded"
|
||||||
: 'bg-gray-800 text-gray-400 hover:text-white hover:bg-gray-700'
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<tab.icon className="h-4 w-4" />
|
Copy Exam Code
|
||||||
<span>{tab.label}</span>
|
|
||||||
</button>
|
</button>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Tab Content */}
|
|
||||||
{activeTab === 'overview' && (
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Statistics Cards */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
|
|
||||||
<div className="bg-gray-800 p-6 rounded-lg">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-sm font-medium text-gray-400">Total Participants</h3>
|
|
||||||
<p className="text-3xl font-bold text-blue-400">{examData.participants.total}</p>
|
|
||||||
</div>
|
|
||||||
<Users className="h-8 w-8 text-blue-400" />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-gray-800 p-6 rounded-lg">
|
{/* Participants List */}
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-sm font-medium text-gray-400">Completed</h3>
|
|
||||||
<p className="text-3xl font-bold text-green-400">{examData.participants.completed}</p>
|
|
||||||
</div>
|
|
||||||
<Trophy className="h-8 w-8 text-green-400" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-gray-800 p-6 rounded-lg">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-sm font-medium text-gray-400">Still Working</h3>
|
|
||||||
<p className="text-3xl font-bold text-yellow-400">{examData.participants.working}</p>
|
|
||||||
</div>
|
|
||||||
<Clock className="h-8 w-8 text-yellow-400" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-gray-800 p-6 rounded-lg">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-sm font-medium text-gray-400">Average Score</h3>
|
|
||||||
<p className="text-3xl font-bold text-purple-400">
|
|
||||||
{Math.round(examData.statistics.average_score)}%
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<BarChart className="h-8 w-8 text-purple-400" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Recent Activity */}
|
|
||||||
<div className="bg-gray-800 rounded-lg p-6">
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
<h3 className="text-lg font-bold mb-4">Recent Participants</h3>
|
<h2 className="text-xl font-bold mb-4 flex items-center space-x-2">
|
||||||
<div className="space-y-2">
|
<Users className="h-5 w-5" />
|
||||||
{examData.participants.recent_joins.slice(0, 5).map((participant, index) => (
|
<span>Participants ({participants.length})</span>
|
||||||
<div key={participant.name} className="flex items-center justify-between p-3 bg-gray-700 rounded">
|
</h2>
|
||||||
<div className="flex items-center space-x-3">
|
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-sm font-bold">
|
|
||||||
{participant.name.charAt(0).toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="font-medium">{participant.name}</div>
|
|
||||||
<div className="text-sm text-gray-400">
|
|
||||||
Joined {new Date(participant.joined_at).toLocaleTimeString()}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<div className={`px-2 py-1 rounded text-xs ${
|
|
||||||
participant.completed ? 'bg-green-900 text-green-200' : 'bg-yellow-900 text-yellow-200'
|
|
||||||
}`}>
|
|
||||||
{participant.completed ? `${participant.score}% completed` : 'Working'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeTab === 'participants' && (
|
|
||||||
<div className="bg-gray-800 rounded-lg overflow-hidden">
|
|
||||||
<div className="p-6 border-b border-gray-700">
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<h3 className="text-lg font-bold">All Participants ({examData.participants.total})</h3>
|
|
||||||
<div className="text-sm text-gray-400">
|
|
||||||
Completion Rate: {Math.round(examData.statistics.completion_rate)}%
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full">
|
<table className="w-full">
|
||||||
<thead className="bg-gray-700">
|
<thead>
|
||||||
<tr>
|
<tr className="border-b border-gray-700">
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Participant</th>
|
<th className="text-left py-3 px-4">Name</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Status</th>
|
<th className="text-left py-3 px-4">Joined At</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Score</th>
|
<th className="text-left py-3 px-4">Status</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Language</th>
|
<th className="text-left py-3 px-4">Score</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Joined</th>
|
<th className="text-left py-3 px-4">Actions</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Actions</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-gray-700">
|
<tbody>
|
||||||
{examData.participants.all_participants.map((participant) => (
|
{participants.map((participant, index) => (
|
||||||
<tr key={participant.name} className="hover:bg-gray-700">
|
<tr key={index} className="border-b border-gray-700 hover:bg-gray-700">
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="py-3 px-4 font-medium">{participant.name}</td>
|
||||||
<div className="flex items-center">
|
<td className="py-3 px-4 text-gray-400">
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-sm font-bold mr-3">
|
{new Date(participant.joined_at).toLocaleTimeString()}
|
||||||
{participant.name.charAt(0).toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div className="font-medium">{participant.name}</div>
|
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="py-3 px-4">
|
||||||
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
|
<span className={`px-2 py-1 rounded text-xs ${
|
||||||
participant.completed
|
participant.completed
|
||||||
? 'bg-green-900 text-green-200'
|
? 'bg-green-600 text-white'
|
||||||
: participant.kicked
|
: 'bg-yellow-600 text-white'
|
||||||
? 'bg-red-900 text-red-200'
|
|
||||||
: 'bg-yellow-900 text-yellow-200'
|
|
||||||
}`}>
|
}`}>
|
||||||
{participant.kicked ? 'Kicked' : participant.completed ? 'Completed' : 'Working'}
|
{participant.completed ? 'Completed' : 'In Progress'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
|
<td className="py-3 px-4">
|
||||||
{participant.completed ? `${participant.score}%` : '-'}
|
{participant.completed ? (
|
||||||
|
<span className="font-bold text-green-400">{participant.score}%</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-gray-500">-</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
|
<td className="py-3 px-4">
|
||||||
{participant.language || '-'}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
|
|
||||||
{new Date(participant.joined_at).toLocaleString()}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => removeParticipant(participant.name)}
|
||||||
setSelectedParticipant(participant.name)
|
className="bg-red-600 hover:bg-red-700 px-3 py-1 rounded text-sm flex items-center space-x-1"
|
||||||
setShowKickModal(true)
|
|
||||||
}}
|
|
||||||
className="text-red-400 hover:text-red-300"
|
|
||||||
title="Remove Participant"
|
|
||||||
>
|
>
|
||||||
<UserX className="h-4 w-4" />
|
<UserMinus className="h-3 w-3" />
|
||||||
|
<span>Remove</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
|
||||||
|
{participants.length === 0 && (
|
||||||
|
<div className="text-center py-8 text-gray-400">
|
||||||
|
No participants have joined yet.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Leaderboard Sidebar */}
|
||||||
|
<div className="w-80 bg-gray-800 p-6">
|
||||||
|
<div className="flex items-center space-x-2 mb-6">
|
||||||
|
<Trophy className="h-6 w-6 text-yellow-400" />
|
||||||
|
<h2 className="text-xl font-bold">Live Leaderboard</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
{activeTab === 'leaderboard' && (
|
|
||||||
<div className="bg-gray-800 rounded-lg p-6">
|
|
||||||
<h3 className="text-lg font-bold mb-6">Live Leaderboard</h3>
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{examData.leaderboard.map((participant, index) => {
|
{leaderboard.map((participant, index) => (
|
||||||
const rankColors = {
|
|
||||||
1: 'bg-gradient-to-r from-yellow-600 to-yellow-500 text-white',
|
|
||||||
2: 'bg-gradient-to-r from-gray-400 to-gray-500 text-white',
|
|
||||||
3: 'bg-gradient-to-r from-orange-600 to-orange-500 text-white'
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
<div
|
||||||
key={participant.name}
|
key={index}
|
||||||
className={`p-4 rounded-lg ${
|
className={`p-4 rounded-lg ${
|
||||||
rankColors[participant.rank as keyof typeof rankColors] || 'bg-gray-700'
|
index === 0 ? 'bg-gradient-to-r from-yellow-600 to-orange-600' :
|
||||||
|
index === 1 ? 'bg-gradient-to-r from-gray-600 to-gray-500' :
|
||||||
|
index === 2 ? 'bg-gradient-to-r from-orange-600 to-red-600' :
|
||||||
|
'bg-gray-700'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex justify-between items-center">
|
||||||
<div className="flex items-center space-x-4">
|
|
||||||
<div className="text-2xl font-bold">#{participant.rank}</div>
|
|
||||||
<div>
|
<div>
|
||||||
<div className="font-bold text-lg">{participant.name}</div>
|
<div className="flex items-center space-x-2">
|
||||||
<div className="text-sm opacity-75">
|
<span className="font-bold text-lg">#{index + 1}</span>
|
||||||
{participant.language && `${participant.language} • `}
|
<span className="font-medium">{participant.name}</span>
|
||||||
Submitted: {new Date(participant.submission_time!).toLocaleTimeString()}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
{participant.submitted_at && (
|
||||||
|
<p className="text-xs text-gray-300 mt-1">
|
||||||
|
Submitted: {new Date(participant.submitted_at).toLocaleTimeString()}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<div className="text-2xl font-bold">{participant.score}%</div>
|
<div className="text-2xl font-bold">{participant.score}%</div>
|
||||||
|
<div className={`text-xs ${participant.completed ? 'text-green-300' : 'text-yellow-300'}`}>
|
||||||
|
{participant.completed ? 'Completed' : 'In Progress'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{leaderboard.length === 0 && (
|
||||||
|
<div className="text-center py-8 text-gray-400">
|
||||||
|
No submissions yet.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{activeTab === 'settings' && (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="bg-gray-800 rounded-lg p-6">
|
|
||||||
<h3 className="text-lg font-bold mb-4">Exam Controls</h3>
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<button
|
<button
|
||||||
onClick={() => extendExam(5)}
|
onClick={fetchLeaderboard}
|
||||||
disabled={examData.exam_info.status !== 'active'}
|
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded text-sm flex items-center justify-center space-x-2"
|
||||||
className="bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-600 px-4 py-2 rounded text-left"
|
|
||||||
>
|
>
|
||||||
<div className="font-medium">Extend by 5 minutes</div>
|
<RefreshCw className="h-4 w-4" />
|
||||||
<div className="text-sm opacity-75">Add more time to the exam</div>
|
<span>Refresh Leaderboard</span>
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => extendExam(15)}
|
|
||||||
disabled={examData.exam_info.status !== 'active'}
|
|
||||||
className="bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-600 px-4 py-2 rounded text-left"
|
|
||||||
>
|
|
||||||
<div className="font-medium">Extend by 15 minutes</div>
|
|
||||||
<div className="text-sm opacity-75">Add significant extra time</div>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={endExam}
|
|
||||||
disabled={examData.exam_info.status !== 'active'}
|
|
||||||
className="bg-red-600 hover:bg-red-700 disabled:bg-gray-600 px-4 py-2 rounded text-left"
|
|
||||||
>
|
|
||||||
<div className="font-medium">End Exam Early</div>
|
|
||||||
<div className="text-sm opacity-75">Stop the exam immediately</div>
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-gray-800 rounded-lg p-6">
|
|
||||||
<h3 className="text-lg font-bold mb-4">Auto-Refresh Settings</h3>
|
|
||||||
<div className="flex items-center space-x-4">
|
|
||||||
<label className="text-sm font-medium">Update Interval:</label>
|
|
||||||
<select
|
|
||||||
value={refreshInterval}
|
|
||||||
onChange={(e) => setRefreshInterval(Number(e.target.value))}
|
|
||||||
className="bg-gray-700 border border-gray-600 rounded px-3 py-1 text-sm"
|
|
||||||
>
|
|
||||||
<option value={1000}>1 second</option>
|
|
||||||
<option value={3000}>3 seconds</option>
|
|
||||||
<option value={5000}>5 seconds</option>
|
|
||||||
<option value={10000}>10 seconds</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Kick Participant Modal */}
|
|
||||||
{showKickModal && selectedParticipant && (
|
|
||||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
|
||||||
<div className="bg-gray-800 rounded-lg p-6 w-full max-w-md">
|
|
||||||
<h3 className="text-lg font-bold mb-4">Remove Participant</h3>
|
|
||||||
<p className="text-gray-300 mb-6">
|
|
||||||
Are you sure you want to remove <strong>"{selectedParticipant}"</strong> from the exam?
|
|
||||||
This action cannot be undone.
|
|
||||||
</p>
|
|
||||||
<div className="flex justify-end space-x-3">
|
|
||||||
<button
|
|
||||||
onClick={() => {
|
|
||||||
setShowKickModal(false)
|
|
||||||
setSelectedParticipant(null)
|
|
||||||
}}
|
|
||||||
className="px-4 py-2 bg-gray-600 hover:bg-gray-700 rounded"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => removeParticipant(selectedParticipant)}
|
|
||||||
className="px-4 py-2 bg-red-600 hover:bg-red-700 rounded"
|
|
||||||
>
|
|
||||||
Remove Participant
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -104,6 +104,7 @@ export default function CodingExamPlatform() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ✅ UPDATED CREATE EXAM WITH HOST PANEL REDIRECT
|
||||||
const createExam = async () => {
|
const createExam = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/exam/create-exam', {
|
const response = await fetch('http://127.0.0.1:5000/api/exam/create-exam', {
|
||||||
@@ -113,7 +114,8 @@ export default function CodingExamPlatform() {
|
|||||||
title: 'String Capitalizer Challenge',
|
title: 'String Capitalizer Challenge',
|
||||||
problem_id: 'string-capitalizer',
|
problem_id: 'string-capitalizer',
|
||||||
duration_minutes: 30,
|
duration_minutes: 30,
|
||||||
host_name: participantName
|
host_name: participantName,
|
||||||
|
max_participants: 50
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -128,14 +130,38 @@ export default function CodingExamPlatform() {
|
|||||||
setExamId(participantCode)
|
setExamId(participantCode)
|
||||||
setExamInfo({ title: 'String Capitalizer Challenge', status: 'waiting' })
|
setExamInfo({ title: 'String Capitalizer Challenge', status: 'waiting' })
|
||||||
|
|
||||||
// ✅ FIXED: Show exam_code instead of exam_id
|
// Store host exam data
|
||||||
alert(`Exam created! Share this code with participants: ${participantCode}`)
|
localStorage.setItem('host_exam', JSON.stringify({
|
||||||
|
exam_code: participantCode,
|
||||||
|
exam_id: databaseId,
|
||||||
|
host_name: participantName,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
exam_details: data.exam_details || {}
|
||||||
|
}))
|
||||||
|
|
||||||
|
// ✅ ENHANCED SUCCESS MESSAGE WITH REDIRECT INFO
|
||||||
|
alert(`✅ Exam Created Successfully!
|
||||||
|
|
||||||
|
📝 Exam Code: ${participantCode}
|
||||||
|
📋 Title: String Capitalizer Challenge
|
||||||
|
👤 Host: ${participantName}
|
||||||
|
⏱️ Duration: 30 minutes
|
||||||
|
|
||||||
|
🔗 Share this code with participants: ${participantCode}
|
||||||
|
|
||||||
|
Redirecting to Host Management Panel...`)
|
||||||
|
|
||||||
|
// ✅ REDIRECT TO HOST PANEL
|
||||||
|
setTimeout(() => {
|
||||||
|
router.push(`/coding/host/${participantCode}`)
|
||||||
|
}, 2000)
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
alert(`Failed to create exam: ${data.error}`)
|
alert(`❌ Failed to create exam: ${data.error}`)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Create exam error:', error)
|
console.error('Create exam error:', error)
|
||||||
alert('Failed to create exam - network error')
|
alert('❌ Failed to create exam - network error')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,6 +342,7 @@ Redirecting to exam interface...`)
|
|||||||
<div className="mt-4 p-3 bg-gray-50 rounded text-xs text-gray-600">
|
<div className="mt-4 p-3 bg-gray-50 rounded text-xs text-gray-600">
|
||||||
<p>Will create with host_name: "{participantName}"</p>
|
<p>Will create with host_name: "{participantName}"</p>
|
||||||
<p>✅ Will display exam_code (6 chars), not exam_id</p>
|
<p>✅ Will display exam_code (6 chars), not exam_id</p>
|
||||||
|
<p>🔄 After creation → redirect to /coding/host/[examCode]</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user