mirror of
https://github.com/th30d4y/OpenLearnX.git
synced 2026-05-26 19:26:33 +00:00
Updated project with latest changes
This commit is contained in:
@@ -47,6 +47,16 @@ except ImportError:
|
|||||||
DASHBOARD_AVAILABLE = False
|
DASHBOARD_AVAILABLE = False
|
||||||
print("⚠️ Dashboard routes not available")
|
print("⚠️ Dashboard routes not available")
|
||||||
|
|
||||||
|
# ✅ Public modules/lessons endpoints for course pages
|
||||||
|
try:
|
||||||
|
from routes.modules_public import bp as modules_public_bp
|
||||||
|
MODULES_PUBLIC_AVAILABLE = True
|
||||||
|
print("✅ Public modules routes available")
|
||||||
|
except ImportError:
|
||||||
|
modules_public_bp = None
|
||||||
|
MODULES_PUBLIC_AVAILABLE = False
|
||||||
|
print("⚠️ Public modules routes not available")
|
||||||
|
|
||||||
# ✅ CRITICAL: Import certificate blueprint
|
# ✅ CRITICAL: Import certificate blueprint
|
||||||
try:
|
try:
|
||||||
from routes.certificate import bp as certificate_bp
|
from routes.certificate import bp as certificate_bp
|
||||||
@@ -64,6 +74,7 @@ blueprints_to_register = [
|
|||||||
('certificate', '/api/certificate'), # ✅ Use blueprint version
|
('certificate', '/api/certificate'), # ✅ Use blueprint version
|
||||||
('dashboard', '/api/dashboard'),
|
('dashboard', '/api/dashboard'),
|
||||||
('courses', '/api/courses'),
|
('courses', '/api/courses'),
|
||||||
|
('modules_public', '/api/modules'),
|
||||||
('quizzes', '/api/quizzes'),
|
('quizzes', '/api/quizzes'),
|
||||||
('admin', '/api/admin'),
|
('admin', '/api/admin'),
|
||||||
('exam', '/api/exam'),
|
('exam', '/api/exam'),
|
||||||
|
|||||||
+83
-8
@@ -202,8 +202,24 @@ def admin_dashboard():
|
|||||||
"""Get admin dashboard statistics"""
|
"""Get admin dashboard statistics"""
|
||||||
try:
|
try:
|
||||||
total_courses = db.courses.count_documents({})
|
total_courses = db.courses.count_documents({})
|
||||||
total_lessons = db.lessons.count_documents({})
|
|
||||||
|
# ✅ FIXED: Count modules and lessons from embedded course structure
|
||||||
|
total_modules = 0
|
||||||
|
total_lessons = 0
|
||||||
|
courses = list(db.courses.find({}, {"modules": 1}))
|
||||||
|
for course in courses:
|
||||||
|
modules = course.get("modules", [])
|
||||||
|
total_modules += len(modules)
|
||||||
|
for module in modules:
|
||||||
|
lessons = module.get("lessons", [])
|
||||||
|
total_lessons += len(lessons)
|
||||||
|
|
||||||
|
# Fallback to separate collections if they exist
|
||||||
|
if total_modules == 0:
|
||||||
total_modules = db.modules.count_documents({})
|
total_modules = db.modules.count_documents({})
|
||||||
|
if total_lessons == 0:
|
||||||
|
total_lessons = db.lessons.count_documents({})
|
||||||
|
|
||||||
total_users = db.users.count_documents({})
|
total_users = db.users.count_documents({})
|
||||||
total_logs = db.security_logs.count_documents({})
|
total_logs = db.security_logs.count_documents({})
|
||||||
active_students = db.users.count_documents({
|
active_students = db.users.count_documents({
|
||||||
@@ -1159,14 +1175,47 @@ def get_admin_courses():
|
|||||||
"""Get all courses for admin management"""
|
"""Get all courses for admin management"""
|
||||||
try:
|
try:
|
||||||
print("Fetching courses from database...")
|
print("Fetching courses from database...")
|
||||||
courses = list(db.courses.find({}, {"_id": 0}))
|
courses = list(db.courses.find({}))
|
||||||
print(f"Found {len(courses)} courses")
|
print(f"Found {len(courses)} courses")
|
||||||
|
|
||||||
|
def normalize_title(value):
|
||||||
|
return " ".join(str(value or "").lower().split())
|
||||||
|
|
||||||
|
def course_score(item):
|
||||||
|
score = 0
|
||||||
|
for field in ["subject", "difficulty", "mentor", "description", "video_url", "embed_url"]:
|
||||||
|
if item.get(field):
|
||||||
|
score += 1
|
||||||
|
if isinstance(item.get("modules"), list):
|
||||||
|
score += min(len(item.get("modules", [])), 5)
|
||||||
|
return score
|
||||||
|
|
||||||
for course in courses:
|
for course in courses:
|
||||||
|
if not course.get("id") and "_id" in course:
|
||||||
|
course["id"] = str(course["_id"])
|
||||||
|
if "_id" in course:
|
||||||
|
del course["_id"]
|
||||||
|
if not course.get("title"):
|
||||||
|
course["title"] = course.get("name", "")
|
||||||
|
if not course.get("subject"):
|
||||||
|
course["subject"] = course.get("category", course.get("topic", ""))
|
||||||
|
if not course.get("difficulty"):
|
||||||
|
course["difficulty"] = course.get("level", "")
|
||||||
|
if not course.get("mentor"):
|
||||||
|
course["mentor"] = course.get("instructor", course.get("instructor_name", course.get("mentor_name", "")))
|
||||||
|
if not course.get("description"):
|
||||||
|
course["description"] = course.get("summary", "")
|
||||||
course["students"] = course.get("students", 0)
|
course["students"] = course.get("students", 0)
|
||||||
course["status"] = "published"
|
course["status"] = "published"
|
||||||
|
|
||||||
return jsonify(courses)
|
deduped = {}
|
||||||
|
for course in courses:
|
||||||
|
key = normalize_title(course.get("title")) or course.get("id")
|
||||||
|
existing = deduped.get(key)
|
||||||
|
if not existing or course_score(course) > course_score(existing):
|
||||||
|
deduped[key] = course
|
||||||
|
|
||||||
|
return jsonify(list(deduped.values()))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error fetching courses: {str(e)}")
|
print(f"Error fetching courses: {str(e)}")
|
||||||
return jsonify({"error": str(e)}), 500
|
return jsonify({"error": str(e)}), 500
|
||||||
@@ -1261,16 +1310,27 @@ def delete_course(course_id):
|
|||||||
try:
|
try:
|
||||||
print(f"Deleting course: {course_id}")
|
print(f"Deleting course: {course_id}")
|
||||||
|
|
||||||
|
course = db.courses.find_one({"id": course_id})
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)})
|
||||||
|
except Exception:
|
||||||
|
course = None
|
||||||
|
|
||||||
|
if not course:
|
||||||
|
return jsonify({"error": "Course not found"}), 404
|
||||||
|
|
||||||
|
course_key = course.get("id") or str(course.get("_id"))
|
||||||
|
|
||||||
# Delete related lessons first
|
# Delete related lessons first
|
||||||
lesson_result = db.lessons.delete_many({"course_id": course_id})
|
lesson_result = db.lessons.delete_many({"course_id": course_key})
|
||||||
print(f"Deleted {lesson_result.deleted_count} related lessons")
|
print(f"Deleted {lesson_result.deleted_count} related lessons")
|
||||||
|
|
||||||
# Delete related modules
|
# Delete related modules
|
||||||
module_result = db.modules.delete_many({"course_id": course_id})
|
module_result = db.modules.delete_many({"course_id": course_key})
|
||||||
print(f"Deleted {module_result.deleted_count} related modules")
|
print(f"Deleted {module_result.deleted_count} related modules")
|
||||||
|
|
||||||
# Delete the course
|
result = db.courses.delete_one({"_id": course.get("_id")})
|
||||||
result = db.courses.delete_one({"id": course_id})
|
|
||||||
|
|
||||||
if result.deleted_count == 0:
|
if result.deleted_count == 0:
|
||||||
return jsonify({"error": "Course not found"}), 404
|
return jsonify({"error": "Course not found"}), 404
|
||||||
@@ -1690,8 +1750,23 @@ def get_admin_stats():
|
|||||||
"""Get detailed admin statistics"""
|
"""Get detailed admin statistics"""
|
||||||
try:
|
try:
|
||||||
total_courses = db.courses.count_documents({})
|
total_courses = db.courses.count_documents({})
|
||||||
total_lessons = db.lessons.count_documents({})
|
|
||||||
|
# ✅ FIXED: Count modules and lessons from embedded course structure
|
||||||
|
total_modules = 0
|
||||||
|
total_lessons = 0
|
||||||
|
courses = list(db.courses.find({}, {"modules": 1}))
|
||||||
|
for course in courses:
|
||||||
|
modules = course.get("modules", [])
|
||||||
|
total_modules += len(modules)
|
||||||
|
for module in modules:
|
||||||
|
lessons = module.get("lessons", [])
|
||||||
|
total_lessons += len(lessons)
|
||||||
|
|
||||||
|
# Fallback to separate collections if they exist
|
||||||
|
if total_modules == 0:
|
||||||
total_modules = db.modules.count_documents({})
|
total_modules = db.modules.count_documents({})
|
||||||
|
if total_lessons == 0:
|
||||||
|
total_lessons = db.lessons.count_documents({})
|
||||||
|
|
||||||
# Course statistics by subject
|
# Course statistics by subject
|
||||||
pipeline = [
|
pipeline = [
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ client = MongoClient(mongo_uri)
|
|||||||
db = client.openlearnx
|
db = client.openlearnx
|
||||||
|
|
||||||
# JWT secret - must be set via environment variable
|
# JWT secret - must be set via environment variable
|
||||||
JWT_SECRET = os.getenv('JWT_SECRET')
|
JWT_SECRET = os.getenv('JWT_SECRET_KEY') or os.getenv('JWT_SECRET')
|
||||||
if not JWT_SECRET:
|
if not JWT_SECRET:
|
||||||
import warnings
|
import warnings
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|||||||
@@ -808,8 +808,19 @@ def get_user_certificates(user_id):
|
|||||||
if db is None:
|
if db is None:
|
||||||
return jsonify({"error": "Database connection failed"}), 500
|
return jsonify({"error": "Database connection failed"}), 500
|
||||||
|
|
||||||
|
normalized_user_id = str(user_id).strip()
|
||||||
|
if normalized_user_id.startswith("0x"):
|
||||||
|
normalized_user_id = normalized_user_id.lower()
|
||||||
|
|
||||||
certificates = list(db.certificates.find(
|
certificates = list(db.certificates.find(
|
||||||
|
{
|
||||||
|
"$or": [
|
||||||
{"user_id": user_id},
|
{"user_id": user_id},
|
||||||
|
{"user_id": normalized_user_id},
|
||||||
|
{"wallet_address": user_id},
|
||||||
|
{"wallet_address": normalized_user_id},
|
||||||
|
]
|
||||||
|
},
|
||||||
{"_id": 0, "encrypted_wallet_id": 0}
|
{"_id": 0, "encrypted_wallet_id": 0}
|
||||||
).sort("created_at", -1))
|
).sort("created_at", -1))
|
||||||
|
|
||||||
|
|||||||
+193
-16
@@ -1,5 +1,6 @@
|
|||||||
from flask import Blueprint, jsonify, current_app, request
|
from flask import Blueprint, jsonify, current_app, request
|
||||||
from pymongo import MongoClient
|
from pymongo import MongoClient
|
||||||
|
from bson import ObjectId
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from activity_logger import log_user_activity, resolve_user_identity
|
from activity_logger import log_user_activity, resolve_user_identity
|
||||||
@@ -16,19 +17,29 @@ db = client.openlearnx
|
|||||||
def list_courses():
|
def list_courses():
|
||||||
"""Get all courses - DYNAMIC from database"""
|
"""Get all courses - DYNAMIC from database"""
|
||||||
try:
|
try:
|
||||||
courses = list(db.courses.find({}, {"_id": 0}))
|
courses = list(db.courses.find({}))
|
||||||
|
|
||||||
course_list = []
|
course_list = []
|
||||||
for course in courses:
|
for course in courses:
|
||||||
|
# Handle both old format (id field) and new format (_id field)
|
||||||
|
course_id = course.get("id") or str(course.get("_id", ""))
|
||||||
|
modules_count = len(course.get("modules", []))
|
||||||
|
if modules_count == 0 and course_id:
|
||||||
|
modules_count = db.modules.count_documents({"course_id": course_id})
|
||||||
course_data = {
|
course_data = {
|
||||||
"id": course.get("id"),
|
"id": course_id,
|
||||||
"title": course.get("title"),
|
"title": course.get("title", ""),
|
||||||
"subject": course.get("subject"),
|
"subject": course.get("subject", ""),
|
||||||
"description": course.get("description"),
|
"description": course.get("description", ""),
|
||||||
"difficulty": course.get("difficulty"),
|
"difficulty": course.get("difficulty", ""),
|
||||||
"mentor": course.get("mentor"),
|
"mentor": course.get("mentor", course.get("instructor", "")),
|
||||||
"video_url": course.get("video_url"),
|
"video_url": course.get("video_url", ""),
|
||||||
"embed_url": course.get("embed_url"),
|
"embed_url": course.get("embed_url", ""),
|
||||||
|
"thumbnail": course.get("thumbnail", ""),
|
||||||
|
"instructor": course.get("instructor", ""),
|
||||||
|
"duration_hours": course.get("duration_hours", 0),
|
||||||
|
"level": course.get("level", ""),
|
||||||
|
"modules": modules_count,
|
||||||
"progress": course.get("progress", 0)
|
"progress": course.get("progress", 0)
|
||||||
}
|
}
|
||||||
course_list.append(course_data)
|
course_list.append(course_data)
|
||||||
@@ -42,26 +53,111 @@ def list_courses():
|
|||||||
def get_course(course_id):
|
def get_course(course_id):
|
||||||
"""Get specific course details - DYNAMIC"""
|
"""Get specific course details - DYNAMIC"""
|
||||||
try:
|
try:
|
||||||
course = db.courses.find_one({"id": course_id}, {"_id": 0})
|
# Try multiple ways to find the course
|
||||||
|
course = None
|
||||||
|
|
||||||
|
# First try as string _id (new UUID format)
|
||||||
|
course = db.courses.find_one({"_id": course_id})
|
||||||
|
|
||||||
|
# If not found, try as ObjectId (old format)
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)})
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# If still not found, try as 'id' field (legacy)
|
||||||
|
if not course:
|
||||||
|
course = db.courses.find_one({"id": course_id})
|
||||||
|
|
||||||
if not course:
|
if not course:
|
||||||
return jsonify({"error": "Course not found"}), 404
|
return jsonify({"error": "Course not found"}), 404
|
||||||
|
|
||||||
|
# Convert ObjectId to string for JSON serialization
|
||||||
|
course_id_value = course.get("id") or str(course.get("_id"))
|
||||||
|
course["id"] = course_id_value
|
||||||
|
course["_id"] = str(course.get("_id"))
|
||||||
|
if not course.get("mentor"):
|
||||||
|
course["mentor"] = course.get("instructor", "")
|
||||||
|
|
||||||
return jsonify(course)
|
return jsonify(course)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error in get_course: {e}")
|
print(f"Error in get_course: {e}")
|
||||||
return jsonify({"error": "Failed to fetch course"}), 500
|
return jsonify({"error": "Failed to fetch course"}), 500
|
||||||
|
|
||||||
|
@bp.route("/<course_id>/modules", methods=["GET"])
|
||||||
|
def get_course_modules(course_id):
|
||||||
|
"""Get modules for a course from modules collection or embedded structure."""
|
||||||
|
try:
|
||||||
|
modules = list(db.modules.find({"course_id": course_id}).sort("order", 1))
|
||||||
|
if not modules:
|
||||||
|
course = db.courses.find_one({"id": course_id})
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)})
|
||||||
|
except Exception:
|
||||||
|
course = None
|
||||||
|
if course:
|
||||||
|
embedded = course.get("modules", [])
|
||||||
|
for module in embedded:
|
||||||
|
module["course_id"] = course_id
|
||||||
|
return jsonify({"success": True, "modules": embedded})
|
||||||
|
|
||||||
|
for module in modules:
|
||||||
|
if "_id" in module:
|
||||||
|
module["id"] = str(module["_id"])
|
||||||
|
del module["_id"]
|
||||||
|
|
||||||
|
return jsonify({"success": True, "modules": modules})
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error fetching modules: {e}")
|
||||||
|
return jsonify({"error": "Failed to fetch modules"}), 500
|
||||||
|
|
||||||
|
@bp.route("/modules/<module_id>/lessons", methods=["GET"])
|
||||||
|
def get_public_module_lessons(module_id):
|
||||||
|
"""Get lessons for a module for public course pages."""
|
||||||
|
try:
|
||||||
|
lessons = list(db.lessons.find({"module_id": module_id}).sort("order", 1))
|
||||||
|
for lesson in lessons:
|
||||||
|
if "_id" in lesson:
|
||||||
|
lesson["id"] = str(lesson["_id"])
|
||||||
|
del lesson["_id"]
|
||||||
|
return jsonify({"success": True, "lessons": lessons})
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error fetching lessons: {e}")
|
||||||
|
return jsonify({"error": "Failed to fetch lessons"}), 500
|
||||||
|
|
||||||
@bp.route("/<course_id>/lessons/<lesson_id>", methods=["GET"])
|
@bp.route("/<course_id>/lessons/<lesson_id>", methods=["GET"])
|
||||||
def get_lesson(course_id, lesson_id):
|
def get_lesson(course_id, lesson_id):
|
||||||
"""Get specific lesson content - DYNAMIC"""
|
"""Get specific lesson content - DYNAMIC"""
|
||||||
try:
|
try:
|
||||||
lesson = db.lessons.find_one({"id": lesson_id, "course_id": course_id}, {"_id": 0})
|
# Find course with either format
|
||||||
|
course = None
|
||||||
|
course = db.courses.find_one({"_id": course_id})
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)})
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
if not course:
|
||||||
|
course = db.courses.find_one({"id": course_id})
|
||||||
|
|
||||||
if not lesson:
|
if not course:
|
||||||
return jsonify({"error": "Lesson not found"}), 404
|
return jsonify({"error": "Course not found"}), 404
|
||||||
|
|
||||||
|
# Search for lesson in embedded modules structure
|
||||||
|
for module in course.get("modules", []):
|
||||||
|
for lesson in module.get("lessons", []):
|
||||||
|
if lesson.get("lesson_id") == lesson_id or lesson.get("id") == lesson_id:
|
||||||
return jsonify(lesson)
|
return jsonify(lesson)
|
||||||
|
|
||||||
|
# Fallback: check lessons collection
|
||||||
|
lesson = db.lessons.find_one({"id": lesson_id, "course_id": course_id})
|
||||||
|
if lesson:
|
||||||
|
lesson["_id"] = str(lesson.get("_id", ""))
|
||||||
|
return jsonify(lesson)
|
||||||
|
|
||||||
|
return jsonify({"error": "Lesson not found"}), 404
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error in get_lesson: {e}")
|
print(f"Error in get_lesson: {e}")
|
||||||
return jsonify({"error": "Failed to fetch lesson"}), 500
|
return jsonify({"error": "Failed to fetch lesson"}), 500
|
||||||
@@ -74,8 +170,30 @@ def mark_lesson_complete(course_id, lesson_id):
|
|||||||
user_id = identity.get("user_id")
|
user_id = identity.get("user_id")
|
||||||
|
|
||||||
if user_id:
|
if user_id:
|
||||||
course = db.courses.find_one({"id": course_id}, {"title": 1}) or {}
|
# Find course with new or old format
|
||||||
lesson = db.lessons.find_one({"id": lesson_id, "course_id": course_id}, {"title": 1}) or {}
|
course = db.courses.find_one({"_id": course_id}, {"title": 1})
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)}, {"title": 1})
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
if not course:
|
||||||
|
course = db.courses.find_one({"id": course_id}, {"title": 1})
|
||||||
|
|
||||||
|
course = course or {}
|
||||||
|
|
||||||
|
# Find lesson title from embedded structure or lessons collection
|
||||||
|
lesson_title = lesson_id
|
||||||
|
course_full = None
|
||||||
|
if course:
|
||||||
|
course_full = db.courses.find_one({"_id": course.get("_id")})
|
||||||
|
|
||||||
|
if course_full:
|
||||||
|
for module in course_full.get("modules", []):
|
||||||
|
for lesson in module.get("lessons", []):
|
||||||
|
if lesson.get("lesson_id") == lesson_id or lesson.get("id") == lesson_id:
|
||||||
|
lesson_title = lesson.get("title", lesson_id)
|
||||||
|
break
|
||||||
|
|
||||||
db.user_courses.update_one(
|
db.user_courses.update_one(
|
||||||
{"user_id": user_id, "course_id": course_id},
|
{"user_id": user_id, "course_id": course_id},
|
||||||
@@ -97,7 +215,7 @@ def mark_lesson_complete(course_id, lesson_id):
|
|||||||
user_id,
|
user_id,
|
||||||
"course",
|
"course",
|
||||||
"Lesson completed",
|
"Lesson completed",
|
||||||
f"Completed lesson '{lesson.get('title', lesson_id)}' in course '{course.get('title', course_id)}'",
|
f"Completed lesson '{lesson_title}' in course '{course.get('title', course_id)}'",
|
||||||
{"course_id": course_id, "lesson_id": lesson_id},
|
{"course_id": course_id, "lesson_id": lesson_id},
|
||||||
points_earned=10,
|
points_earned=10,
|
||||||
)
|
)
|
||||||
@@ -170,6 +288,65 @@ def log_course_activity(course_id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"error": str(e)}), 500
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
|
@bp.route("/<course_id>/register", methods=["POST"])
|
||||||
|
def register_course(course_id):
|
||||||
|
"""Register/enroll a user in a course and log a dashboard notification."""
|
||||||
|
try:
|
||||||
|
identity = resolve_user_identity(request, db)
|
||||||
|
user_id = identity.get("user_id")
|
||||||
|
if not user_id:
|
||||||
|
return jsonify({"success": False, "error": "Authentication required"}), 401
|
||||||
|
|
||||||
|
course = db.courses.find_one({"id": course_id}, {"title": 1})
|
||||||
|
if not course:
|
||||||
|
try:
|
||||||
|
course = db.courses.find_one({"_id": ObjectId(course_id)}, {"title": 1})
|
||||||
|
except Exception:
|
||||||
|
course = None
|
||||||
|
course_title = course.get("title") if course else course_id
|
||||||
|
|
||||||
|
db.user_courses.update_one(
|
||||||
|
{"user_id": user_id, "course_id": course_id},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"user_id": user_id,
|
||||||
|
"course_id": course_id,
|
||||||
|
"enrolled": True,
|
||||||
|
"enrolled_at": datetime.utcnow(),
|
||||||
|
"last_activity_at": datetime.utcnow(),
|
||||||
|
},
|
||||||
|
"$setOnInsert": {"completed": False, "lessons_completed": []},
|
||||||
|
},
|
||||||
|
upsert=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
log_user_activity(
|
||||||
|
db,
|
||||||
|
user_id,
|
||||||
|
"course",
|
||||||
|
"Course registered",
|
||||||
|
f"Registered for course '{course_title}'",
|
||||||
|
{"course_id": course_id},
|
||||||
|
)
|
||||||
|
|
||||||
|
return jsonify({"success": True})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
|
@bp.route("/<course_id>/registration", methods=["GET"])
|
||||||
|
def get_course_registration(course_id):
|
||||||
|
"""Check whether the current user is registered for a course."""
|
||||||
|
try:
|
||||||
|
identity = resolve_user_identity(request, db)
|
||||||
|
user_id = identity.get("user_id")
|
||||||
|
if not user_id:
|
||||||
|
return jsonify({"success": False, "registered": False, "error": "Authentication required"}), 401
|
||||||
|
|
||||||
|
record = db.user_courses.find_one({"user_id": user_id, "course_id": course_id})
|
||||||
|
return jsonify({"success": True, "registered": bool(record)})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
@bp.route("/<course_id>/progress", methods=["GET"])
|
@bp.route("/<course_id>/progress", methods=["GET"])
|
||||||
def get_course_progress(course_id):
|
def get_course_progress(course_id):
|
||||||
"""Get user's progress in a specific course"""
|
"""Get user's progress in a specific course"""
|
||||||
|
|||||||
+60
-21
@@ -28,15 +28,31 @@ def verify_wallet_authentication():
|
|||||||
# ✅ FIXED: Verify JWT signature using JWT_SECRET_KEY
|
# ✅ FIXED: Verify JWT signature using JWT_SECRET_KEY
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
jwt_secret = current_app.config.get('JWT_SECRET_KEY') or os.getenv('JWT_SECRET_KEY')
|
jwt_secret = current_app.config.get('JWT_SECRET_KEY') or os.getenv('JWT_SECRET_KEY')
|
||||||
|
fallback_secret = os.getenv('JWT_SECRET')
|
||||||
|
decoded = None
|
||||||
|
|
||||||
if jwt_secret:
|
if jwt_secret:
|
||||||
|
try:
|
||||||
decoded = jwt.decode(
|
decoded = jwt.decode(
|
||||||
token,
|
token,
|
||||||
jwt_secret,
|
jwt_secret,
|
||||||
algorithms=["HS256", "RS256"]
|
algorithms=["HS256", "RS256"],
|
||||||
)
|
)
|
||||||
else:
|
except Exception as e:
|
||||||
logger.error("JWT_SECRET_KEY not configured")
|
logger.warning(f"⚠️ JWT decode failed with JWT_SECRET_KEY: {e}")
|
||||||
decoded = None
|
|
||||||
|
if decoded is None and fallback_secret:
|
||||||
|
try:
|
||||||
|
decoded = jwt.decode(
|
||||||
|
token,
|
||||||
|
fallback_secret,
|
||||||
|
algorithms=["HS256", "RS256"],
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ JWT decode failed with JWT_SECRET: {e}")
|
||||||
|
|
||||||
|
if decoded is None:
|
||||||
|
logger.error("JWT secrets not configured or token invalid")
|
||||||
|
|
||||||
if decoded:
|
if decoded:
|
||||||
user_id = decoded.get('sub') or decoded.get('user_id') or decoded.get('uid') or decoded.get('wallet_address')
|
user_id = decoded.get('sub') or decoded.get('user_id') or decoded.get('uid') or decoded.get('wallet_address')
|
||||||
@@ -140,13 +156,33 @@ def get_comprehensive_stats():
|
|||||||
"wallet_address": wallet_address
|
"wallet_address": wallet_address
|
||||||
})
|
})
|
||||||
|
|
||||||
|
identity_candidates = {str(user_id)}
|
||||||
|
if wallet_address:
|
||||||
|
identity_candidates.add(str(wallet_address).lower())
|
||||||
|
|
||||||
|
# Resolve user identity aliases to avoid missing data across auth methods.
|
||||||
|
user_doc = None
|
||||||
|
try:
|
||||||
|
maybe_oid = ObjectId(str(user_id))
|
||||||
|
user_doc = db.users.find_one({"_id": maybe_oid})
|
||||||
|
except Exception:
|
||||||
|
user_doc = db.users.find_one({"wallet_address": str(user_id).lower()}) or db.users.find_one({"email": str(user_id).lower()})
|
||||||
|
|
||||||
|
if user_doc:
|
||||||
|
if user_doc.get("_id"):
|
||||||
|
identity_candidates.add(str(user_doc.get("_id")))
|
||||||
|
if user_doc.get("wallet_address"):
|
||||||
|
identity_candidates.add(str(user_doc.get("wallet_address")).lower())
|
||||||
|
if user_doc.get("email"):
|
||||||
|
identity_candidates.add(str(user_doc.get("email")).lower())
|
||||||
|
|
||||||
# ✅ FETCH ONLY REAL DATA FROM MONGODB
|
# ✅ FETCH ONLY REAL DATA FROM MONGODB
|
||||||
user_stats = db.user_stats.find_one({"user_id": user_id})
|
user_stats = db.user_stats.find_one({"user_id": {"$in": list(identity_candidates)}})
|
||||||
courses = list(db.user_courses.find({"user_id": user_id}))
|
courses = list(db.user_courses.find({"user_id": {"$in": list(identity_candidates)}}))
|
||||||
quizzes = list(db.user_quizzes.find({"user_id": user_id}))
|
quizzes = list(db.user_quizzes.find({"user_id": {"$in": list(identity_candidates)}}))
|
||||||
coding_submissions = list(db.user_submissions.find({"user_id": user_id}))
|
coding_submissions = list(db.user_submissions.find({"user_id": {"$in": list(identity_candidates)}}))
|
||||||
blockchain_data = db.user_blockchain.find_one({"user_id": user_id})
|
blockchain_data = db.user_blockchain.find_one({"user_id": {"$in": list(identity_candidates)}})
|
||||||
achievements = list(db.user_achievements.find({"user_id": user_id}))
|
achievements = list(db.user_achievements.find({"user_id": {"$in": list(identity_candidates)}}))
|
||||||
|
|
||||||
# Convert ObjectIds to strings for JSON serialization
|
# Convert ObjectIds to strings for JSON serialization
|
||||||
for collection in [courses, quizzes, coding_submissions, achievements]:
|
for collection in [courses, quizzes, coding_submissions, achievements]:
|
||||||
@@ -185,7 +221,8 @@ def get_comprehensive_stats():
|
|||||||
|
|
||||||
# Real calculations (no fake data)
|
# Real calculations (no fake data)
|
||||||
total_xp = calculate_real_total_xp(courses, quizzes, coding_submissions, achievements)
|
total_xp = calculate_real_total_xp(courses, quizzes, coding_submissions, achievements)
|
||||||
courses_completed = len([c for c in courses if c.get('completed', False)])
|
completed_courses = len([c for c in courses if c.get('completed', False)])
|
||||||
|
courses_completed = len(courses) if courses else completed_courses
|
||||||
coding_problems_solved = len(coding_submissions)
|
coding_problems_solved = len(coding_submissions)
|
||||||
quiz_accuracy = calculate_real_quiz_accuracy(quizzes)
|
quiz_accuracy = calculate_real_quiz_accuracy(quizzes)
|
||||||
coding_streak = calculate_real_coding_streak(coding_submissions)
|
coding_streak = calculate_real_coding_streak(coding_submissions)
|
||||||
@@ -197,6 +234,7 @@ def get_comprehensive_stats():
|
|||||||
comprehensive_stats = {
|
comprehensive_stats = {
|
||||||
"total_xp": total_xp,
|
"total_xp": total_xp,
|
||||||
"courses_completed": courses_completed,
|
"courses_completed": courses_completed,
|
||||||
|
"completed_courses": completed_courses,
|
||||||
"coding_problems_solved": coding_problems_solved,
|
"coding_problems_solved": coding_problems_solved,
|
||||||
"quiz_accuracy": quiz_accuracy,
|
"quiz_accuracy": quiz_accuracy,
|
||||||
"streak_data": {
|
"streak_data": {
|
||||||
@@ -206,7 +244,7 @@ def get_comprehensive_stats():
|
|||||||
},
|
},
|
||||||
"total_courses": len(courses),
|
"total_courses": len(courses),
|
||||||
"total_quizzes": len(quizzes),
|
"total_quizzes": len(quizzes),
|
||||||
"global_rank": calculate_real_global_rank(user_stats, user_id) if user_stats else 0,
|
"global_rank": calculate_real_global_rank(user_stats, user_id, total_xp),
|
||||||
"weekly_activity": weekly_activity,
|
"weekly_activity": weekly_activity,
|
||||||
"monthly_goals": {
|
"monthly_goals": {
|
||||||
"target": user_stats.get('monthly_target', 0) if user_stats else 0,
|
"target": user_stats.get('monthly_target', 0) if user_stats else 0,
|
||||||
@@ -766,10 +804,10 @@ def get_empty_stats(wallet_address=None):
|
|||||||
|
|
||||||
def calculate_real_total_xp(courses, quizzes, submissions, achievements):
|
def calculate_real_total_xp(courses, quizzes, submissions, achievements):
|
||||||
"""Calculate total XP from ONLY real MongoDB data"""
|
"""Calculate total XP from ONLY real MongoDB data"""
|
||||||
course_xp = sum([c.get('points', 0) for c in courses if c.get('completed', False)])
|
course_xp = sum([c.get('points', 0) or 0 for c in courses if c.get('completed', False)])
|
||||||
quiz_xp = sum([q.get('points', 0) for q in quizzes])
|
quiz_xp = sum([q.get('points', q.get('score', 0) or 0) or 0 for q in quizzes])
|
||||||
coding_xp = sum([s.get('points_earned', 0) for s in submissions])
|
coding_xp = sum([s.get('points_earned', s.get('score', 0) or 0) or 0 for s in submissions])
|
||||||
achievement_xp = sum([a.get('points', 0) for a in achievements])
|
achievement_xp = sum([a.get('points', 0) or 0 for a in achievements])
|
||||||
|
|
||||||
total = course_xp + quiz_xp + coding_xp + achievement_xp
|
total = course_xp + quiz_xp + coding_xp + achievement_xp
|
||||||
logger.info(f"📊 Real XP calculation: courses={course_xp}, quizzes={quiz_xp}, coding={coding_xp}, achievements={achievement_xp}, total={total}")
|
logger.info(f"📊 Real XP calculation: courses={course_xp}, quizzes={quiz_xp}, coding={coding_xp}, achievements={achievement_xp}, total={total}")
|
||||||
@@ -853,16 +891,17 @@ def calculate_real_quiz_accuracy(quizzes):
|
|||||||
logger.info(f"📊 Real quiz accuracy: {accuracy}% from {len(quizzes)} quizzes")
|
logger.info(f"📊 Real quiz accuracy: {accuracy}% from {len(quizzes)} quizzes")
|
||||||
return accuracy
|
return accuracy
|
||||||
|
|
||||||
def calculate_real_global_rank(user_stats, user_id):
|
def calculate_real_global_rank(user_stats, user_id, total_xp=None):
|
||||||
"""Calculate global rank from ONLY real MongoDB data"""
|
"""Calculate global rank from ONLY real MongoDB data"""
|
||||||
if not user_stats:
|
user_xp = None
|
||||||
return 0
|
if user_stats:
|
||||||
|
|
||||||
user_xp = user_stats.get('total_xp', 0)
|
user_xp = user_stats.get('total_xp', 0)
|
||||||
|
if user_xp is None:
|
||||||
|
user_xp = total_xp or 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
higher_ranked = db.user_stats.count_documents({"total_xp": {"$gt": user_xp}})
|
higher_ranked = db.user_stats.count_documents({"total_xp": {"$gt": user_xp}})
|
||||||
rank = higher_ranked + 1
|
rank = higher_ranked + 1 if user_xp > 0 else 0
|
||||||
logger.info(f"📊 Real global rank: {rank} (XP: {user_xp})")
|
logger.info(f"📊 Real global rank: {rank} (XP: {user_xp})")
|
||||||
return rank
|
return rank
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from flask import Blueprint, jsonify
|
||||||
|
from pymongo import MongoClient
|
||||||
|
from bson import ObjectId
|
||||||
|
import os
|
||||||
|
|
||||||
|
bp = Blueprint("modules_public", __name__)
|
||||||
|
|
||||||
|
mongo_uri = os.getenv("MONGODB_URI", "mongodb://localhost:27017/")
|
||||||
|
client = MongoClient(mongo_uri)
|
||||||
|
db = client.openlearnx
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/<module_id>/lessons", methods=["GET"])
|
||||||
|
def get_public_module_lessons(module_id):
|
||||||
|
"""Public: get lessons for a module by module id."""
|
||||||
|
try:
|
||||||
|
lessons = list(db.lessons.find({"module_id": module_id}).sort("order", 1))
|
||||||
|
if not lessons:
|
||||||
|
try:
|
||||||
|
oid = ObjectId(module_id)
|
||||||
|
lessons = list(db.lessons.find({"module_id": oid}).sort("order", 1))
|
||||||
|
except Exception:
|
||||||
|
lessons = []
|
||||||
|
|
||||||
|
for lesson in lessons:
|
||||||
|
if "_id" in lesson:
|
||||||
|
lesson["id"] = str(lesson["_id"])
|
||||||
|
del lesson["_id"]
|
||||||
|
|
||||||
|
return jsonify({"success": True, "lessons": lessons})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": f"Failed to fetch lessons: {str(e)}"}), 500
|
||||||
@@ -229,7 +229,6 @@ class RealCompilerService:
|
|||||||
"compile",
|
"compile",
|
||||||
"__import__",
|
"__import__",
|
||||||
"open",
|
"open",
|
||||||
"input",
|
|
||||||
"globals",
|
"globals",
|
||||||
"locals",
|
"locals",
|
||||||
"vars",
|
"vars",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { Edit, Plus, Trash2 } from "lucide-react"
|
import { Edit, Plus, Trash2, ListTree } from "lucide-react"
|
||||||
|
|
||||||
type Course = {
|
type Course = {
|
||||||
id: string
|
id: string
|
||||||
@@ -15,6 +15,26 @@ type Course = {
|
|||||||
students: number
|
students: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Module = {
|
||||||
|
id: string
|
||||||
|
course_id: string
|
||||||
|
title: string
|
||||||
|
description?: string
|
||||||
|
order: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type Lesson = {
|
||||||
|
id: string
|
||||||
|
module_id: string
|
||||||
|
course_id: string
|
||||||
|
title: string
|
||||||
|
description?: string
|
||||||
|
video_url?: string
|
||||||
|
order: number
|
||||||
|
duration?: string
|
||||||
|
type?: string
|
||||||
|
}
|
||||||
|
|
||||||
const API_BASE = "http://127.0.0.1:5000"
|
const API_BASE = "http://127.0.0.1:5000"
|
||||||
|
|
||||||
export default function AdminCoursesPage() {
|
export default function AdminCoursesPage() {
|
||||||
@@ -24,6 +44,7 @@ export default function AdminCoursesPage() {
|
|||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [showAdd, setShowAdd] = useState(false)
|
const [showAdd, setShowAdd] = useState(false)
|
||||||
const [editing, setEditing] = useState<Course | null>(null)
|
const [editing, setEditing] = useState<Course | null>(null)
|
||||||
|
const [managing, setManaging] = useState<Course | null>(null)
|
||||||
|
|
||||||
const getToken = () => localStorage.getItem("admin_token")
|
const getToken = () => localStorage.getItem("admin_token")
|
||||||
const headers = () => {
|
const headers = () => {
|
||||||
@@ -160,12 +181,19 @@ export default function AdminCoursesPage() {
|
|||||||
courses.map((course) => (
|
courses.map((course) => (
|
||||||
<tr key={course.id}>
|
<tr key={course.id}>
|
||||||
<td className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">{course.title}</td>
|
<td className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">{course.title}</td>
|
||||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.subject}</td>
|
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.subject?.trim() || "—"}</td>
|
||||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.difficulty}</td>
|
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.difficulty?.trim() || "—"}</td>
|
||||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.mentor}</td>
|
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.mentor?.trim() || "—"}</td>
|
||||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{Number(course.students || 0).toLocaleString()}</td>
|
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{Number(course.students || 0).toLocaleString()}</td>
|
||||||
<td className="px-4 py-3 text-sm">
|
<td className="px-4 py-3 text-sm">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setManaging(course)}
|
||||||
|
className="rounded p-1.5 text-indigo-600 hover:bg-indigo-50 dark:hover:bg-indigo-950/30"
|
||||||
|
title="Manage modules & lessons"
|
||||||
|
>
|
||||||
|
<ListTree className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => setEditing(course)}
|
onClick={() => setEditing(course)}
|
||||||
className="rounded p-1.5 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950/30"
|
className="rounded p-1.5 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950/30"
|
||||||
@@ -201,6 +229,13 @@ export default function AdminCoursesPage() {
|
|||||||
onSubmit={(payload) => saveCourse(payload, editing?.id)}
|
onSubmit={(payload) => saveCourse(payload, editing?.id)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{managing && (
|
||||||
|
<CourseContentModal
|
||||||
|
course={managing}
|
||||||
|
onClose={() => setManaging(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -293,3 +328,326 @@ function CourseFormModal({
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function CourseContentModal({
|
||||||
|
course,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
course: Course
|
||||||
|
onClose: () => void
|
||||||
|
}) {
|
||||||
|
const [modules, setModules] = useState<Module[]>([])
|
||||||
|
const [lessonsByModule, setLessonsByModule] = useState<Record<string, Lesson[]>>({})
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [moduleForm, setModuleForm] = useState({
|
||||||
|
title: "",
|
||||||
|
description: "",
|
||||||
|
order: 1,
|
||||||
|
})
|
||||||
|
const [lessonModuleId, setLessonModuleId] = useState<string | null>(null)
|
||||||
|
const [lessonForm, setLessonForm] = useState({
|
||||||
|
title: "",
|
||||||
|
description: "",
|
||||||
|
video_url: "",
|
||||||
|
order: 1,
|
||||||
|
duration: "",
|
||||||
|
type: "video",
|
||||||
|
})
|
||||||
|
|
||||||
|
const adminHeaders = () => {
|
||||||
|
const token = localStorage.getItem("admin_token")
|
||||||
|
return token
|
||||||
|
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||||
|
: { "Content-Type": "application/json" }
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadModules = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${API_BASE}/api/admin/courses/${course.id}/modules`, {
|
||||||
|
headers: adminHeaders(),
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
setModules([])
|
||||||
|
setLessonsByModule({})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const data = await resp.json()
|
||||||
|
const list = Array.isArray(data?.modules) ? data.modules : Array.isArray(data) ? data : []
|
||||||
|
list.sort((a: Module, b: Module) => (a.order || 0) - (b.order || 0))
|
||||||
|
setModules(list)
|
||||||
|
|
||||||
|
const lessonsMap: Record<string, Lesson[]> = {}
|
||||||
|
await Promise.all(
|
||||||
|
list.map(async (module: Module) => {
|
||||||
|
const lessonsResp = await fetch(`${API_BASE}/api/admin/modules/${module.id}/lessons`, {
|
||||||
|
headers: adminHeaders(),
|
||||||
|
})
|
||||||
|
if (!lessonsResp.ok) {
|
||||||
|
lessonsMap[module.id] = []
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const lessonsData = await lessonsResp.json()
|
||||||
|
const lessonsList = Array.isArray(lessonsData?.lessons)
|
||||||
|
? lessonsData.lessons
|
||||||
|
: Array.isArray(lessonsData)
|
||||||
|
? lessonsData
|
||||||
|
: []
|
||||||
|
lessonsList.sort((a: Lesson, b: Lesson) => (a.order || 0) - (b.order || 0))
|
||||||
|
lessonsMap[module.id] = lessonsList
|
||||||
|
})
|
||||||
|
)
|
||||||
|
setLessonsByModule(lessonsMap)
|
||||||
|
setModuleForm((prev) => ({ ...prev, order: list.length + 1 }))
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const createModule = async () => {
|
||||||
|
if (!moduleForm.title.trim()) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${API_BASE}/api/admin/courses/${course.id}/modules`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: adminHeaders(),
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: moduleForm.title.trim(),
|
||||||
|
description: moduleForm.description.trim(),
|
||||||
|
order: Number(moduleForm.order) || 1,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
alert("Failed to create module")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setModuleForm({ title: "", description: "", order: moduleForm.order + 1 })
|
||||||
|
await loadModules()
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteModule = async (moduleId: string) => {
|
||||||
|
if (!confirm("Delete this module and all its lessons?")) return
|
||||||
|
const resp = await fetch(`${API_BASE}/api/admin/modules/${moduleId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: adminHeaders(),
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
alert("Failed to delete module")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await loadModules()
|
||||||
|
}
|
||||||
|
|
||||||
|
const createLesson = async (moduleId: string) => {
|
||||||
|
if (!lessonForm.title.trim()) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${API_BASE}/api/admin/modules/${moduleId}/lessons`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: adminHeaders(),
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: lessonForm.title.trim(),
|
||||||
|
description: lessonForm.description.trim(),
|
||||||
|
video_url: lessonForm.video_url.trim(),
|
||||||
|
order: Number(lessonForm.order) || 1,
|
||||||
|
duration: lessonForm.duration.trim() || undefined,
|
||||||
|
type: lessonForm.type.trim() || "video",
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
alert("Failed to create lesson")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setLessonForm({ title: "", description: "", video_url: "", order: lessonForm.order + 1, duration: "", type: "video" })
|
||||||
|
setLessonModuleId(null)
|
||||||
|
await loadModules()
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteLesson = async (lessonId: string) => {
|
||||||
|
if (!confirm("Delete this lesson?")) return
|
||||||
|
const resp = await fetch(`${API_BASE}/api/admin/lessons/${lessonId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: adminHeaders(),
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
alert("Failed to delete lesson")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await loadModules()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadModules()
|
||||||
|
}, [course.id])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/35 p-4">
|
||||||
|
<div className="w-full max-w-5xl rounded-xl border border-gray-200 bg-white p-6 shadow-xl dark:border-gray-800 dark:bg-gray-900">
|
||||||
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Manage Modules & Lessons</h3>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400">{course.title}</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={onClose} className="rounded-md bg-gray-100 px-3 py-2 text-sm hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700">
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||||
|
<div className="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
|
||||||
|
<h4 className="text-sm font-semibold text-gray-900 dark:text-white">Add Module</h4>
|
||||||
|
<div className="mt-3 grid gap-3">
|
||||||
|
<input
|
||||||
|
placeholder="Module title"
|
||||||
|
value={moduleForm.title}
|
||||||
|
onChange={(e) => setModuleForm({ ...moduleForm, title: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<textarea
|
||||||
|
placeholder="Module description"
|
||||||
|
value={moduleForm.description}
|
||||||
|
onChange={(e) => setModuleForm({ ...moduleForm, description: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Order"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={moduleForm.order}
|
||||||
|
onChange={(e) => setModuleForm({ ...moduleForm, order: Number(e.target.value) || 1 })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={createModule}
|
||||||
|
disabled={saving}
|
||||||
|
className="self-start rounded-md bg-blue-600 px-3 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{saving ? "Saving..." : "Add Module"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
|
||||||
|
<h4 className="text-sm font-semibold text-gray-900 dark:text-white">Modules</h4>
|
||||||
|
{loading ? (
|
||||||
|
<p className="mt-3 text-sm text-gray-600 dark:text-gray-400">Loading modules...</p>
|
||||||
|
) : modules.length === 0 ? (
|
||||||
|
<p className="mt-3 text-sm text-gray-600 dark:text-gray-400">No modules yet.</p>
|
||||||
|
) : (
|
||||||
|
<div className="mt-3 space-y-3">
|
||||||
|
{modules.map((module) => (
|
||||||
|
<div key={module.id} className="rounded-md border border-gray-200 p-3 dark:border-gray-700">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-semibold text-gray-900 dark:text-white">{module.title}</div>
|
||||||
|
<div className="text-xs text-gray-500 dark:text-gray-400">Order {module.order}</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setLessonModuleId(module.id)}
|
||||||
|
className="rounded-md bg-indigo-600 px-2 py-1 text-xs text-white hover:bg-indigo-700"
|
||||||
|
>
|
||||||
|
Add Lesson
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => deleteModule(module.id)}
|
||||||
|
className="rounded-md bg-red-600 px-2 py-1 text-xs text-white hover:bg-red-700"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-2 space-y-2">
|
||||||
|
{(lessonsByModule[module.id] || []).map((lesson) => (
|
||||||
|
<div key={lesson.id} className="flex items-center justify-between rounded-md bg-gray-50 px-2 py-1 text-xs dark:bg-gray-800">
|
||||||
|
<span className="text-gray-700 dark:text-gray-300">
|
||||||
|
{lesson.order}. {lesson.title}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => deleteLesson(lesson.id)}
|
||||||
|
className="text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{lessonModuleId === module.id && (
|
||||||
|
<div className="mt-3 grid gap-2 rounded-md border border-gray-200 p-3 dark:border-gray-700">
|
||||||
|
<input
|
||||||
|
placeholder="Lesson title"
|
||||||
|
value={lessonForm.title}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, title: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Lesson description"
|
||||||
|
value={lessonForm.description}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, description: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Video URL"
|
||||||
|
value={lessonForm.video_url}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, video_url: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<div className="grid grid-cols-1 gap-2 md:grid-cols-3">
|
||||||
|
<input
|
||||||
|
placeholder="Order"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={lessonForm.order}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, order: Number(e.target.value) || 1 })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Duration"
|
||||||
|
value={lessonForm.duration}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, duration: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Type"
|
||||||
|
value={lessonForm.type}
|
||||||
|
onChange={(e) => setLessonForm({ ...lessonForm, type: e.target.value })}
|
||||||
|
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => createLesson(module.id)}
|
||||||
|
disabled={saving}
|
||||||
|
className="rounded-md bg-blue-600 px-3 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{saving ? "Saving..." : "Save Lesson"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setLessonModuleId(null)}
|
||||||
|
className="rounded-md bg-gray-100 px-3 py-2 text-sm hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ export default function LessonDetailPage() {
|
|||||||
const [currentLesson, setCurrentLesson] = useState<Lesson | null>(null)
|
const [currentLesson, setCurrentLesson] = useState<Lesson | null>(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [resolvedCourseId, setResolvedCourseId] = useState<string | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAuthLoading && !user) {
|
if (!isAuthLoading && !user) {
|
||||||
@@ -84,9 +85,11 @@ export default function LessonDetailPage() {
|
|||||||
const courseData = courseResponse.data
|
const courseData = courseResponse.data
|
||||||
console.log('✅ Course data loaded:', courseData)
|
console.log('✅ Course data loaded:', courseData)
|
||||||
setCourse(courseData)
|
setCourse(courseData)
|
||||||
|
const targetId = courseData.id || courseId
|
||||||
|
setResolvedCourseId(targetId)
|
||||||
|
|
||||||
// Fetch modules for the course
|
// Fetch modules for the course
|
||||||
const modulesResponse = await fetch(`http://127.0.0.1:5000/api/courses/${courseId}/modules`, {
|
const modulesResponse = await fetch(`http://127.0.0.1:5000/api/courses/${targetId}/modules`, {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
@@ -144,7 +147,7 @@ export default function LessonDetailPage() {
|
|||||||
} else if (lessonId) {
|
} else if (lessonId) {
|
||||||
console.log('❌ Lesson not found:', lessonId)
|
console.log('❌ Lesson not found:', lessonId)
|
||||||
toast.error("Lesson not found")
|
toast.error("Lesson not found")
|
||||||
router.replace(`/courses/${courseId}`)
|
router.replace(`/courses/${targetId}`)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Failed to fetch modules')
|
throw new Error('Failed to fetch modules')
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ type Course = {
|
|||||||
subject: string
|
subject: string
|
||||||
difficulty: string
|
difficulty: string
|
||||||
mentor: string
|
mentor: string
|
||||||
students: number
|
students?: number
|
||||||
embed_url?: string
|
embed_url?: string
|
||||||
video_url?: string
|
video_url?: string
|
||||||
}
|
}
|
||||||
@@ -55,6 +55,9 @@ export default function CoursePage() {
|
|||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [modulesLoading, setModulesLoading] = useState(false)
|
const [modulesLoading, setModulesLoading] = useState(false)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [resolvedCourseId, setResolvedCourseId] = useState<string | null>(null)
|
||||||
|
const [isRegistering, setIsRegistering] = useState(false)
|
||||||
|
const [isRegistered, setIsRegistered] = useState(false)
|
||||||
|
|
||||||
const [selectedModuleId, setSelectedModuleId] = useState<string | null>(null)
|
const [selectedModuleId, setSelectedModuleId] = useState<string | null>(null)
|
||||||
const [selectedLessonId, setSelectedLessonId] = useState<string | null>(null)
|
const [selectedLessonId, setSelectedLessonId] = useState<string | null>(null)
|
||||||
@@ -62,10 +65,15 @@ export default function CoursePage() {
|
|||||||
const [completed, setCompleted] = useState(false)
|
const [completed, setCompleted] = useState(false)
|
||||||
const [showCertificateModal, setShowCertificateModal] = useState(false)
|
const [showCertificateModal, setShowCertificateModal] = useState(false)
|
||||||
|
|
||||||
const logCourseActivity = async (action: "view" | "start" | "lesson_view", lessonId?: string) => {
|
const logCourseActivity = async (
|
||||||
|
action: "view" | "start" | "lesson_view",
|
||||||
|
lessonId?: string,
|
||||||
|
overrideCourseId?: string,
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem("openlearnx_jwt_token") || localStorage.getItem("openlearnx_token")
|
const token = localStorage.getItem("openlearnx_jwt_token") || localStorage.getItem("openlearnx_token")
|
||||||
await fetch(`http://127.0.0.1:5000/api/courses/${courseId}/activity`, {
|
const targetCourseId = overrideCourseId || courseId
|
||||||
|
await fetch(`http://127.0.0.1:5000/api/courses/${targetCourseId}/activity`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -89,15 +97,36 @@ export default function CoursePage() {
|
|||||||
}
|
}
|
||||||
}, [authLoading, user, courseId, router])
|
}, [authLoading, user, courseId, router])
|
||||||
|
|
||||||
|
const fetchRegistrationStatus = async (targetId: string) => {
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem("openlearnx_jwt_token") || localStorage.getItem("openlearnx_token")
|
||||||
|
const resp = await fetch(`http://127.0.0.1:5000/api/courses/${targetId}/registration`, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!resp.ok) return
|
||||||
|
const data = await resp.json()
|
||||||
|
if (data?.success) setIsRegistered(Boolean(data.registered))
|
||||||
|
} catch {
|
||||||
|
// Ignore registration fetch errors.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const fetchCourseData = async () => {
|
const fetchCourseData = async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const courseResponse = await api.get<Course>(`/api/courses/${courseId}?t=${Date.now()}`)
|
const courseResponse = await api.get<Course>(`/api/courses/${courseId}?t=${Date.now()}`)
|
||||||
setCourse(courseResponse.data)
|
const courseData = courseResponse.data
|
||||||
logCourseActivity("view")
|
const targetId = courseData.id || courseId
|
||||||
await fetchModulesAndLessons(courseId)
|
setCourse(courseData)
|
||||||
|
setResolvedCourseId(targetId)
|
||||||
|
logCourseActivity("view", undefined, targetId)
|
||||||
|
await fetchRegistrationStatus(targetId)
|
||||||
|
await fetchModulesAndLessons(targetId)
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message || "Failed to load course data.")
|
setError(err.message || "Failed to load course data.")
|
||||||
toast.error("Failed to load course data.")
|
toast.error("Failed to load course data.")
|
||||||
@@ -201,7 +230,31 @@ export default function CoursePage() {
|
|||||||
setSelectedModuleId(moduleId)
|
setSelectedModuleId(moduleId)
|
||||||
setSelectedLessonId(lessonId)
|
setSelectedLessonId(lessonId)
|
||||||
setExpandedModules((prev) => ({ ...prev, [moduleId]: true }))
|
setExpandedModules((prev) => ({ ...prev, [moduleId]: true }))
|
||||||
logCourseActivity("lesson_view", lessonId)
|
logCourseActivity("lesson_view", lessonId, resolvedCourseId || undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRegister = async () => {
|
||||||
|
if (!resolvedCourseId) return
|
||||||
|
setIsRegistering(true)
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem("openlearnx_jwt_token") || localStorage.getItem("openlearnx_token")
|
||||||
|
const resp = await fetch(`http://127.0.0.1:5000/api/courses/${resolvedCourseId}/register`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
const err = await resp.json().catch(() => ({ error: "Registration failed" }))
|
||||||
|
toast.error(err.error || "Registration failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setIsRegistered(true)
|
||||||
|
toast.success("Registered for this course")
|
||||||
|
} finally {
|
||||||
|
setIsRegistering(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getCurrentLesson = (): Lesson | null => {
|
const getCurrentLesson = (): Lesson | null => {
|
||||||
@@ -308,9 +361,18 @@ export default function CoursePage() {
|
|||||||
<div className="w-full px-6 sm:px-8 lg:px-12 py-5 flex flex-wrap items-center justify-between gap-3">
|
<div className="w-full px-6 sm:px-8 lg:px-12 py-5 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">{course.title}</h1>
|
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">{course.title}</h1>
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-300">by {course.mentor}</p>
|
<p className="text-sm text-gray-600 dark:text-gray-300">by {course.mentor || "OpenLearnX Instructor"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap items-center gap-3 text-sm text-gray-700 dark:text-gray-300">
|
<div className="flex flex-wrap items-center gap-3 text-sm text-gray-700 dark:text-gray-300">
|
||||||
|
{!isRegistered && (
|
||||||
|
<button
|
||||||
|
onClick={handleRegister}
|
||||||
|
disabled={isRegistering}
|
||||||
|
className="rounded-full bg-blue-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{isRegistering ? "Registering..." : "Register"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div className="inline-flex items-center gap-2 rounded-full bg-gray-100 dark:bg-gray-700 px-3 py-1.5">
|
<div className="inline-flex items-center gap-2 rounded-full bg-gray-100 dark:bg-gray-700 px-3 py-1.5">
|
||||||
<BookOpen className="w-4 h-4" />
|
<BookOpen className="w-4 h-4" />
|
||||||
<span>{modules.length} modules</span>
|
<span>{modules.length} modules</span>
|
||||||
@@ -321,7 +383,7 @@ export default function CoursePage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="inline-flex items-center gap-2 rounded-full bg-gray-100 dark:bg-gray-700 px-3 py-1.5">
|
<div className="inline-flex items-center gap-2 rounded-full bg-gray-100 dark:bg-gray-700 px-3 py-1.5">
|
||||||
<Users className="w-4 h-4" />
|
<Users className="w-4 h-4" />
|
||||||
<span>{course.students.toLocaleString()} students</span>
|
<span>{Number(course.students || 0).toLocaleString()} students</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -41,6 +41,16 @@ type ActivityData = {
|
|||||||
points_earned?: number
|
points_earned?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CertificateItem = {
|
||||||
|
certificate_id: string
|
||||||
|
course_title: string
|
||||||
|
completion_date: string
|
||||||
|
instructor_name?: string
|
||||||
|
mentor_name?: string
|
||||||
|
public_url?: string
|
||||||
|
unique_url?: string
|
||||||
|
}
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const { user, walletConnected, logout, authMethod } = useAuth()
|
const { user, walletConnected, logout, authMethod } = useAuth()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
@@ -58,6 +68,7 @@ export default function DashboardPage() {
|
|||||||
const [isUploadingImage, setIsUploadingImage] = useState(false)
|
const [isUploadingImage, setIsUploadingImage] = useState(false)
|
||||||
const [showAllActivities, setShowAllActivities] = useState(false)
|
const [showAllActivities, setShowAllActivities] = useState(false)
|
||||||
const [recentActivity, setRecentActivity] = useState<ActivityData[]>([])
|
const [recentActivity, setRecentActivity] = useState<ActivityData[]>([])
|
||||||
|
const [certificates, setCertificates] = useState<CertificateItem[]>([])
|
||||||
const [profileData, setProfileData] = useState({
|
const [profileData, setProfileData] = useState({
|
||||||
name: user?.name || '',
|
name: user?.name || '',
|
||||||
bio: user?.bio || '',
|
bio: user?.bio || '',
|
||||||
@@ -93,13 +104,13 @@ export default function DashboardPage() {
|
|||||||
const fetchRealStats = async () => {
|
const fetchRealStats = async () => {
|
||||||
setIsLoadingStats(true)
|
setIsLoadingStats(true)
|
||||||
try {
|
try {
|
||||||
const [statsResponse, activityResponse] = await Promise.all([
|
const [statsResult, activityResult] = await Promise.allSettled([
|
||||||
api.get("/api/dashboard/comprehensive-stats"),
|
api.get("/api/dashboard/comprehensive-stats"),
|
||||||
api.get("/api/dashboard/recent-activity"),
|
api.get("/api/dashboard/recent-activity"),
|
||||||
])
|
])
|
||||||
|
|
||||||
if (statsResponse.data.success && statsResponse.data.data) {
|
if (statsResult.status === "fulfilled" && statsResult.value.data.success && statsResult.value.data.data) {
|
||||||
const data = statsResponse.data.data
|
const data = statsResult.value.data.data
|
||||||
const streakData = data.streak_data || {}
|
const streakData = data.streak_data || {}
|
||||||
setStats({
|
setStats({
|
||||||
coursesCompleted: data.courses_completed || 0,
|
coursesCompleted: data.courses_completed || 0,
|
||||||
@@ -113,12 +124,25 @@ export default function DashboardPage() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (activityResponse.data?.success && Array.isArray(activityResponse.data?.data)) {
|
if (activityResult.status === "fulfilled" && activityResult.value.data?.success && Array.isArray(activityResult.value.data?.data)) {
|
||||||
setRecentActivity(activityResponse.data.data)
|
setRecentActivity(activityResult.value.data.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user?.id) {
|
||||||
|
const certUserId = user.wallet_address || user.id
|
||||||
|
try {
|
||||||
|
const certResponse = await api.get(`/api/certificate/user/${certUserId}`)
|
||||||
|
if (certResponse.data?.success && Array.isArray(certResponse.data?.certificates)) {
|
||||||
|
setCertificates(certResponse.data.certificates)
|
||||||
|
} else if (Array.isArray(certResponse.data)) {
|
||||||
|
setCertificates(certResponse.data)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore certificate fetch errors.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("Failed to fetch dashboard stats:", error)
|
console.error("Failed to fetch dashboard stats:", error)
|
||||||
// Keep default values if fetch fails
|
|
||||||
toast.error("Failed to load dashboard data")
|
toast.error("Failed to load dashboard data")
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingStats(false)
|
setIsLoadingStats(false)
|
||||||
@@ -878,6 +902,49 @@ export default function DashboardPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Certificates */}
|
||||||
|
<div className="lg:col-span-3">
|
||||||
|
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-6">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h3 className="text-xl font-bold text-gray-900 dark:text-white">Your Certificates</h3>
|
||||||
|
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
|
{certificates.length} total
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{certificates.length === 0 ? (
|
||||||
|
<div className="text-sm text-gray-500 dark:text-gray-400">No certificates yet.</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
{certificates.map((cert) => (
|
||||||
|
<a
|
||||||
|
key={cert.certificate_id}
|
||||||
|
href={cert.public_url || cert.unique_url || `/certificate/${cert.certificate_id}`}
|
||||||
|
className="group rounded-xl border border-gray-200 dark:border-gray-700 p-4 hover:shadow-md hover:border-indigo-300 dark:hover:border-indigo-500 transition-all"
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-900 dark:text-white group-hover:text-indigo-600">
|
||||||
|
{cert.course_title || "Course Certificate"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||||
|
Instructor: {cert.instructor_name || cert.mentor_name || "OpenLearnX"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||||
|
Completed: {new Date(cert.completion_date).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs font-mono text-indigo-600 bg-indigo-50 dark:bg-indigo-900/30 px-2 py-1 rounded">
|
||||||
|
{cert.certificate_id}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -36,10 +36,10 @@ export function CertificateModal({
|
|||||||
courseMentor,
|
courseMentor,
|
||||||
courseId,
|
courseId,
|
||||||
userId,
|
userId,
|
||||||
walletId
|
walletId,
|
||||||
}: CertificateModalProps) {
|
}: CertificateModalProps) {
|
||||||
const [step, setStep] = useState<'input' | 'generating' | 'completed'>('input')
|
const [step, setStep] = useState<"input" | "generating" | "completed">("input")
|
||||||
const [userName, setUserName] = useState('')
|
const [userName, setUserName] = useState("")
|
||||||
const [certificate, setCertificate] = useState<Certificate | null>(null)
|
const [certificate, setCertificate] = useState<Certificate | null>(null)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
|
|
||||||
@@ -52,29 +52,25 @@ export function CertificateModal({
|
|||||||
}
|
}
|
||||||
|
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setStep('generating')
|
setStep("generating")
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('🎓 Generating certificate for STUDENT:', userName.trim())
|
const response = await fetch("http://127.0.0.1:5000/api/certificate/mint", {
|
||||||
|
method: "POST",
|
||||||
const response = await fetch('http://127.0.0.1:5000/api/certificate/mint', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
user_name: userName.trim(),
|
user_name: userName.trim(),
|
||||||
course_id: courseId,
|
course_id: courseId,
|
||||||
wallet_id: walletId,
|
wallet_id: walletId,
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
course_title: courseTitle
|
course_title: courseTitle,
|
||||||
})
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
console.log('✅ Certificate API response:', data)
|
|
||||||
|
|
||||||
const certificateData = data.certificate
|
const certificateData = data.certificate
|
||||||
|
|
||||||
const certificateWithWallet = {
|
const certificateWithWallet = {
|
||||||
@@ -89,25 +85,20 @@ export function CertificateModal({
|
|||||||
share_code: certificateData.share_code,
|
share_code: certificateData.share_code,
|
||||||
public_url: certificateData.public_url,
|
public_url: certificateData.public_url,
|
||||||
unique_url: certificateData.unique_url,
|
unique_url: certificateData.unique_url,
|
||||||
message: certificateData.message
|
message: certificateData.message,
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('🎯 Certificate data:', certificateWithWallet)
|
|
||||||
console.log('🆔 Unique Certificate ID:', certificateWithWallet.certificate_id)
|
|
||||||
|
|
||||||
setCertificate(certificateWithWallet)
|
setCertificate(certificateWithWallet)
|
||||||
setStep('completed')
|
setStep("completed")
|
||||||
toast.success(`Certificate generated for ${certificateWithWallet.user_name}! 🎉`)
|
toast.success(`Certificate generated for ${certificateWithWallet.user_name}!`)
|
||||||
} else {
|
} else {
|
||||||
const error = await response.json()
|
const error = await response.json()
|
||||||
console.error('❌ Certificate error:', error)
|
|
||||||
toast.error(error.error || "Failed to generate certificate")
|
toast.error(error.error || "Failed to generate certificate")
|
||||||
setStep('input')
|
setStep("input")
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Certificate generation error:', error)
|
|
||||||
toast.error("Failed to generate certificate. Please check your connection.")
|
toast.error("Failed to generate certificate. Please check your connection.")
|
||||||
setStep('input')
|
setStep("input")
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
@@ -125,51 +116,48 @@ export function CertificateModal({
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<style>
|
<style>
|
||||||
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Inter:wght@400;500;600&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Inter:wght@400;500;600&display=swap');
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: 'Inter', sans-serif;
|
font-family: 'Inter', sans-serif;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 40px;
|
padding: 40px;
|
||||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
background: #f1f5f9;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.certificate {
|
.certificate {
|
||||||
background: white;
|
background: white;
|
||||||
max-width: 800px;
|
max-width: 960px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 60px;
|
padding: 70px;
|
||||||
border-radius: 20px;
|
border-radius: 6px;
|
||||||
box-shadow: 0 25px 50px rgba(0,0,0,0.15);
|
box-shadow: 0 20px 40px rgba(15, 23, 42, 0.15);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
position: relative;
|
position: relative;
|
||||||
border: 8px solid #4f46e5;
|
border: 4px solid #1f2937;
|
||||||
}
|
}
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
font-family: 'Playfair Display', serif;
|
font-family: 'Playfair Display', serif;
|
||||||
font-size: 42px;
|
font-size: 40px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: #4f46e5;
|
color: #0f172a;
|
||||||
margin: 20px 0;
|
margin: 12px 0 20px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.15em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.student-name {
|
.student-name {
|
||||||
font-family: 'Playfair Display', serif;
|
font-family: 'Playfair Display', serif;
|
||||||
font-size: 48px;
|
font-size: 46px;
|
||||||
color: #1f2937;
|
color: #0f172a;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
margin: 40px 0;
|
margin: 30px 0;
|
||||||
padding: 20px 0;
|
padding: 16px 0;
|
||||||
border-top: 3px solid #4f46e5;
|
border-top: 2px solid #cbd5f5;
|
||||||
border-bottom: 3px solid #4f46e5;
|
border-bottom: 2px solid #cbd5f5;
|
||||||
text-transform: capitalize;
|
text-transform: capitalize;
|
||||||
}
|
}
|
||||||
|
|
||||||
.course-title {
|
.course-title {
|
||||||
font-family: 'Playfair Display', serif;
|
font-family: 'Playfair Display', serif;
|
||||||
font-size: 28px;
|
font-size: 28px;
|
||||||
@@ -178,16 +166,14 @@ export function CertificateModal({
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wallet-container {
|
.wallet-container {
|
||||||
background: #f3f4f6;
|
background: #f8fafc;
|
||||||
border: 2px dashed #9333ea;
|
border: 1px dashed #64748b;
|
||||||
border-radius: 12px;
|
border-radius: 6px;
|
||||||
padding: 15px;
|
padding: 12px;
|
||||||
margin: 25px auto;
|
margin: 25px auto;
|
||||||
max-width: 500px;
|
max-width: 560px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wallet-address {
|
.wallet-address {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: #7c3aed;
|
color: #7c3aed;
|
||||||
@@ -195,78 +181,67 @@ export function CertificateModal({
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
word-break: break-all;
|
word-break: break-all;
|
||||||
}
|
}
|
||||||
|
|
||||||
.date {
|
.date {
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
color: #374151;
|
color: #374151;
|
||||||
margin: 20px 0;
|
margin: 20px 0;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mentor-section {
|
.mentor-section {
|
||||||
margin-top: 50px;
|
margin-top: 40px;
|
||||||
padding-top: 30px;
|
padding-top: 24px;
|
||||||
border-top: 2px solid #e5e7eb;
|
border-top: 1px solid #e2e8f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mentor-name {
|
.mentor-name {
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
color: #1f2937;
|
color: #1f2937;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cert-id {
|
.cert-id {
|
||||||
font-size: 14px;
|
font-size: 13px;
|
||||||
color: #9ca3af;
|
color: #64748b;
|
||||||
margin-top: 20px;
|
margin-top: 18px;
|
||||||
font-family: 'Courier New', monospace;
|
font-family: 'Courier New', monospace;
|
||||||
background: #f9fafb;
|
background: #f8fafc;
|
||||||
padding: 10px;
|
padding: 8px;
|
||||||
border-radius: 8px;
|
border-radius: 6px;
|
||||||
border: 1px solid #e5e7eb;
|
border: 1px solid #e2e8f0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="certificate">
|
<div class="certificate">
|
||||||
<div style="font-size: 60px; margin-bottom: 20px;">🏆</div>
|
<div style="font-size: 48px; margin-bottom: 12px;">🏅</div>
|
||||||
<h1 class="title">CERTIFICATE OF COMPLETION</h1>
|
<h1 class="title">Certificate of Completion</h1>
|
||||||
|
<div style="font-size: 16px; color: #64748b; margin-bottom: 28px;">This is to certify that</div>
|
||||||
<div style="font-size: 18px; color: #6b7280; margin-bottom: 30px;">This is to certify that</div>
|
|
||||||
|
|
||||||
<div class="student-name">${certificate.user_name}</div>
|
<div class="student-name">${certificate.user_name}</div>
|
||||||
|
|
||||||
<div class="wallet-container">
|
<div class="wallet-container">
|
||||||
<div style="font-size: 14px; color: #374151; margin-bottom: 8px; font-weight: 600;">Blockchain Wallet Address</div>
|
<div style="font-size: 14px; color: #374151; margin-bottom: 8px; font-weight: 600;">Blockchain Wallet Address</div>
|
||||||
<div class="wallet-address">${certificate.wallet_address}</div>
|
<div class="wallet-address">${certificate.wallet_address}</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div style="font-size: 16px; color: #64748b; margin-bottom: 18px;">has successfully completed the course</div>
|
||||||
<div style="font-size: 18px; color: #6b7280; margin-bottom: 20px;">has successfully completed the course</div>
|
|
||||||
<div class="course-title">"${certificate.course_title}"</div>
|
<div class="course-title">"${certificate.course_title}"</div>
|
||||||
|
<div class="date">Completed on: ${new Date(certificate.completion_date).toLocaleDateString("en-US", {
|
||||||
<div class="date">✅ Completed on: ${new Date(certificate.completion_date).toLocaleDateString('en-US', {
|
year: "numeric",
|
||||||
year: 'numeric',
|
month: "long",
|
||||||
month: 'long',
|
day: "numeric",
|
||||||
day: 'numeric'
|
|
||||||
})}</div>
|
})}</div>
|
||||||
|
|
||||||
<div class="mentor-section">
|
<div class="mentor-section">
|
||||||
<div style="width: 200px; height: 2px; background: #6b7280; margin: 0 auto 10px auto;"></div>
|
<div style="width: 200px; height: 2px; background: #6b7280; margin: 0 auto 10px auto;"></div>
|
||||||
<div class="mentor-name">${certificate.mentor_name}</div>
|
<div class="mentor-name">${certificate.mentor_name}</div>
|
||||||
<div style="font-size: 14px; color: #6b7280; margin-top: 5px;">Course Instructor</div>
|
<div style="font-size: 14px; color: #6b7280; margin-top: 5px;">Course Instructor</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cert-id">
|
<div class="cert-id">
|
||||||
<strong>Certificate ID: ${certificate.certificate_id}</strong><br>
|
<strong>Certificate ID: ${certificate.certificate_id}</strong><br>
|
||||||
OpenLearnX Learning Platform<br>
|
OpenLearnX Learning Platform<br>
|
||||||
<span style="color: #7c3aed;">🔒 Blockchain Verified Completion</span>
|
<span style="color: #7c3aed;">Blockchain Verified Completion</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`
|
`
|
||||||
|
|
||||||
const printWindow = window.open('', '_blank')
|
const printWindow = window.open("", "_blank")
|
||||||
if (printWindow) {
|
if (printWindow) {
|
||||||
printWindow.document.write(certificateHTML)
|
printWindow.document.write(certificateHTML)
|
||||||
printWindow.document.close()
|
printWindow.document.close()
|
||||||
@@ -282,9 +257,7 @@ export function CertificateModal({
|
|||||||
} else {
|
} else {
|
||||||
toast.error("Popup blocked. Please allow popups and try again.")
|
toast.error("Popup blocked. Please allow popups and try again.")
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('PDF generation error:', error)
|
|
||||||
toast.error("Failed to generate PDF")
|
toast.error("Failed to generate PDF")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -292,40 +265,22 @@ export function CertificateModal({
|
|||||||
const handleShareCertificate = async () => {
|
const handleShareCertificate = async () => {
|
||||||
if (!certificate) return
|
if (!certificate) return
|
||||||
|
|
||||||
const shareText = `🎓 I just completed "${certificate.course_title}" on OpenLearnX!\n\n👤 Student: ${certificate.user_name}\n🏆 Certificate ID: ${certificate.certificate_id}\n🔗 View: ${certificate.public_url || window.location.origin + certificate.unique_url}\n\n#OpenLearnX #Blockchain #Learning`
|
const shareText = `🎓 I just completed "${certificate.course_title}" on OpenLearnX!\n\n👤 Student: ${certificate.user_name}\n🏆 Certificate ID: ${certificate.certificate_id}\n🔗 View: ${certificate.public_url || window.location.origin + certificate.unique_url}\n\n#OpenLearnX #Learning`
|
||||||
|
|
||||||
if (navigator.share) {
|
if (navigator.share) {
|
||||||
try {
|
try {
|
||||||
await navigator.share({
|
await navigator.share({
|
||||||
title: `Certificate of Completion - ${certificate.course_title}`,
|
title: `Certificate of Completion - ${certificate.course_title}`,
|
||||||
text: shareText,
|
text: shareText,
|
||||||
url: certificate.public_url || `${window.location.origin}${certificate.unique_url}`
|
url: certificate.public_url || `${window.location.origin}${certificate.unique_url}`,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Track share
|
|
||||||
try {
|
|
||||||
await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, {
|
|
||||||
method: 'POST'
|
|
||||||
})
|
|
||||||
} catch (e) {
|
|
||||||
console.log('Share tracking failed:', e)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Share cancelled')
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(shareText)
|
await navigator.clipboard.writeText(shareText)
|
||||||
toast.success("Certificate details copied to clipboard!")
|
toast.success("Certificate details copied to clipboard!")
|
||||||
|
|
||||||
// Track share
|
|
||||||
try {
|
|
||||||
await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, {
|
|
||||||
method: 'POST'
|
|
||||||
})
|
|
||||||
} catch (e) {
|
|
||||||
console.log('Share tracking failed:', e)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error("Failed to copy certificate details")
|
toast.error("Failed to copy certificate details")
|
||||||
}
|
}
|
||||||
@@ -333,8 +288,8 @@ export function CertificateModal({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setStep('input')
|
setStep("input")
|
||||||
setUserName('')
|
setUserName("")
|
||||||
setCertificate(null)
|
setCertificate(null)
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
onClose()
|
onClose()
|
||||||
@@ -343,9 +298,7 @@ export function CertificateModal({
|
|||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||||
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
|
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||||
|
{step === "input" && (
|
||||||
{/* Step 1: Name Input */}
|
|
||||||
{step === 'input' && (
|
|
||||||
<>
|
<>
|
||||||
<div className="px-8 py-6 border-b border-gray-200 flex justify-between items-center">
|
<div className="px-8 py-6 border-b border-gray-200 flex justify-between items-center">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
@@ -433,29 +386,22 @@ export function CertificateModal({
|
|||||||
disabled={!userName.trim() || loading}
|
disabled={!userName.trim() || loading}
|
||||||
className="flex-1 px-6 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:from-purple-700 hover:to-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium transition-all"
|
className="flex-1 px-6 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:from-purple-700 hover:to-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium transition-all"
|
||||||
>
|
>
|
||||||
{loading ? 'Generating...' : 'Generate Certificate'}
|
{loading ? "Generating..." : "Generate Certificate"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Step 2: Generating */}
|
{step === "generating" && (
|
||||||
{step === 'generating' && (
|
|
||||||
<div className="px-8 py-12 text-center">
|
<div className="px-8 py-12 text-center">
|
||||||
<div className="animate-spin rounded-full h-16 w-16 border-b-2 border-indigo-600 mx-auto mb-6"></div>
|
<div className="animate-spin rounded-full h-16 w-16 border-b-2 border-indigo-600 mx-auto mb-6"></div>
|
||||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">Generating Your Certificate</h3>
|
<h3 className="text-xl font-semibold text-gray-900 mb-2">Generating Your Certificate</h3>
|
||||||
<p className="text-gray-600">Creating unique certificate ID and blockchain verification...</p>
|
<p className="text-gray-600">Creating unique certificate ID and blockchain verification...</p>
|
||||||
<div className="mt-4 flex items-center justify-center space-x-2 text-sm text-gray-500">
|
|
||||||
<div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce"></div>
|
|
||||||
<div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
|
|
||||||
<div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Step 3: Certificate Generated */}
|
{step === "completed" && certificate && (
|
||||||
{step === 'completed' && certificate && (
|
|
||||||
<>
|
<>
|
||||||
<div className="px-8 py-6 border-b border-gray-200 flex justify-between items-center">
|
<div className="px-8 py-6 border-b border-gray-200 flex justify-between items-center">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
@@ -473,66 +419,57 @@ export function CertificateModal({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="p-8">
|
<div className="p-8">
|
||||||
<div className="bg-gradient-to-br from-purple-50 to-indigo-50 border-4 border-indigo-200 rounded-xl p-8 mb-8 text-center relative overflow-hidden">
|
<div className="bg-gradient-to-br from-slate-50 to-white border-2 border-slate-300 rounded-md p-10 mb-8 text-center relative overflow-hidden shadow-inner">
|
||||||
<div className="absolute top-4 right-4 bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-semibold flex items-center space-x-1">
|
<div className="absolute top-4 right-4 bg-emerald-100 text-emerald-800 px-3 py-1 rounded-full text-xs font-semibold flex items-center space-x-1">
|
||||||
<CheckCircle className="w-3 h-3" />
|
<CheckCircle className="w-3 h-3" />
|
||||||
<span>Verified</span>
|
<span>Verified</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-4xl mb-4">🏆</div>
|
<div className="absolute inset-0 pointer-events-none opacity-10">
|
||||||
<h3 className="text-2xl font-bold text-gray-900 mb-2">CERTIFICATE OF COMPLETION</h3>
|
<div className="w-64 h-64 border-8 border-indigo-500 rounded-full absolute -top-20 -left-20"></div>
|
||||||
<p className="text-gray-600 mb-6">This is to certify that</p>
|
<div className="w-64 h-64 border-8 border-emerald-500 rounded-full absolute -bottom-24 -right-24"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="mb-6">
|
<div className="relative">
|
||||||
<h4 className="text-4xl font-bold text-indigo-600 mb-3 border-b-2 border-indigo-300 pb-2 inline-block capitalize">
|
<div className="text-sm tracking-[0.2em] text-slate-500 font-semibold">OPENLEARNX</div>
|
||||||
|
<h3 className="text-3xl font-serif font-semibold text-slate-900 mt-2">Certificate of Completion</h3>
|
||||||
|
<div className="mt-6 text-sm text-slate-600">This certifies that</div>
|
||||||
|
|
||||||
|
<div className="mt-4 mb-6">
|
||||||
|
<h4 className="text-4xl font-serif font-bold text-indigo-700 border-b border-slate-300 pb-2 inline-block capitalize">
|
||||||
{certificate.user_name}
|
{certificate.user_name}
|
||||||
</h4>
|
</h4>
|
||||||
<p className="text-sm text-gray-500 mt-2">Student</p>
|
<p className="text-xs text-slate-500 mt-2">Student</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-6">
|
<div className="mb-5 text-sm text-slate-600">has successfully completed the course</div>
|
||||||
<p className="text-sm text-gray-500 mb-2">Blockchain Wallet Address:</p>
|
<div className="text-2xl font-serif font-semibold text-slate-900 mb-3">"{certificate.course_title}"</div>
|
||||||
<div className="bg-purple-100 border-2 border-dashed border-purple-300 rounded-lg p-3 mx-auto max-w-md">
|
|
||||||
<p className="text-purple-700 font-mono text-sm break-all">
|
<div className="text-xs text-slate-500 mb-6">
|
||||||
{certificate.wallet_address}
|
Completed on: {new Date(certificate.completion_date).toLocaleDateString("en-US", {
|
||||||
</p>
|
year: "numeric",
|
||||||
</div>
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="text-gray-600 mb-2">has successfully completed the course</p>
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-center">
|
||||||
<h5 className="text-xl font-semibold text-gray-900 mb-4 italic">"{certificate.course_title}"</h5>
|
<div className="text-left">
|
||||||
|
<div className="text-xs text-slate-500">Instructor</div>
|
||||||
<div className="text-sm text-gray-500 mb-6">
|
<div className="text-sm font-semibold text-slate-800">{certificate.mentor_name}</div>
|
||||||
<p>Completed on: {new Date(certificate.completion_date).toLocaleDateString('en-US', {
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric'
|
|
||||||
})}</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 pt-6 border-t border-indigo-200">
|
|
||||||
<div className="flex justify-center">
|
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="w-32 h-0.5 bg-gray-400 mb-2 mx-auto"></div>
|
<div className="inline-block px-4 py-2 border border-slate-300 rounded-md text-xs text-slate-600 font-mono">
|
||||||
<p className="text-base font-semibold text-gray-700">
|
ID: {certificate.certificate_id}
|
||||||
{certificate.mentor_name}
|
</div>
|
||||||
</p>
|
</div>
|
||||||
<p className="text-xs text-gray-500">Course Instructor</p>
|
<div className="text-right">
|
||||||
|
<div className="text-xs text-slate-500">Wallet</div>
|
||||||
|
<div className="text-xs text-indigo-700 font-mono break-all">
|
||||||
|
{certificate.wallet_address}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-6 pt-4 border-t border-indigo-200">
|
|
||||||
<div className="bg-gray-50 rounded-lg p-4 border">
|
|
||||||
<p className="text-sm font-semibold text-gray-700 mb-2">🆔 Unique Certificate ID:</p>
|
|
||||||
<p className="text-lg font-mono font-bold text-indigo-600 bg-white px-3 py-2 rounded border">
|
|
||||||
{certificate.certificate_id}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-gray-500 mt-4">
|
|
||||||
<strong>OpenLearnX Learning Platform</strong><br/>
|
|
||||||
<span className="text-purple-600">🔒 Blockchain Verified Completion</span>
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -555,7 +492,7 @@ export function CertificateModal({
|
|||||||
|
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-gray-500">
|
||||||
🎉 Your certificate with unique ID <strong>{certificate.certificate_id}</strong> has been generated!
|
Your certificate with unique ID <strong>{certificate.certificate_id}</strong> has been generated.
|
||||||
</p>
|
</p>
|
||||||
{certificate.unique_url && (
|
{certificate.unique_url && (
|
||||||
<p className="text-xs text-gray-400 mt-2">
|
<p className="text-xs text-gray-400 mt-2">
|
||||||
|
|||||||
Reference in New Issue
Block a user