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:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Edit, Plus, Trash2 } from "lucide-react"
|
||||
import { Edit, Plus, Trash2, ListTree } from "lucide-react"
|
||||
|
||||
type Course = {
|
||||
id: string
|
||||
@@ -15,6 +15,26 @@ type Course = {
|
||||
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"
|
||||
|
||||
export default function AdminCoursesPage() {
|
||||
@@ -24,6 +44,7 @@ export default function AdminCoursesPage() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showAdd, setShowAdd] = useState(false)
|
||||
const [editing, setEditing] = useState<Course | null>(null)
|
||||
const [managing, setManaging] = useState<Course | null>(null)
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
@@ -160,12 +181,19 @@ export default function AdminCoursesPage() {
|
||||
courses.map((course) => (
|
||||
<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 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.difficulty}</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.subject?.trim() || "—"}</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?.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">
|
||||
<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
|
||||
onClick={() => setEditing(course)}
|
||||
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)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{managing && (
|
||||
<CourseContentModal
|
||||
course={managing}
|
||||
onClose={() => setManaging(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -293,3 +328,326 @@ function CourseFormModal({
|
||||
</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 [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [resolvedCourseId, setResolvedCourseId] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthLoading && !user) {
|
||||
@@ -84,9 +85,11 @@ export default function LessonDetailPage() {
|
||||
const courseData = courseResponse.data
|
||||
console.log('✅ Course data loaded:', courseData)
|
||||
setCourse(courseData)
|
||||
const targetId = courseData.id || courseId
|
||||
setResolvedCourseId(targetId)
|
||||
|
||||
// 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: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
@@ -144,7 +147,7 @@ export default function LessonDetailPage() {
|
||||
} else if (lessonId) {
|
||||
console.log('❌ Lesson not found:', lessonId)
|
||||
toast.error("Lesson not found")
|
||||
router.replace(`/courses/${courseId}`)
|
||||
router.replace(`/courses/${targetId}`)
|
||||
}
|
||||
} else {
|
||||
throw new Error('Failed to fetch modules')
|
||||
|
||||
@@ -15,7 +15,7 @@ type Course = {
|
||||
subject: string
|
||||
difficulty: string
|
||||
mentor: string
|
||||
students: number
|
||||
students?: number
|
||||
embed_url?: string
|
||||
video_url?: string
|
||||
}
|
||||
@@ -55,6 +55,9 @@ export default function CoursePage() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [modulesLoading, setModulesLoading] = useState(false)
|
||||
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 [selectedLessonId, setSelectedLessonId] = useState<string | null>(null)
|
||||
@@ -62,10 +65,15 @@ export default function CoursePage() {
|
||||
const [completed, setCompleted] = 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 {
|
||||
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",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -89,15 +97,36 @@ export default function CoursePage() {
|
||||
}
|
||||
}, [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 () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const courseResponse = await api.get<Course>(`/api/courses/${courseId}?t=${Date.now()}`)
|
||||
setCourse(courseResponse.data)
|
||||
logCourseActivity("view")
|
||||
await fetchModulesAndLessons(courseId)
|
||||
const courseData = courseResponse.data
|
||||
const targetId = courseData.id || courseId
|
||||
setCourse(courseData)
|
||||
setResolvedCourseId(targetId)
|
||||
logCourseActivity("view", undefined, targetId)
|
||||
await fetchRegistrationStatus(targetId)
|
||||
await fetchModulesAndLessons(targetId)
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to load course data.")
|
||||
toast.error("Failed to load course data.")
|
||||
@@ -201,7 +230,31 @@ export default function CoursePage() {
|
||||
setSelectedModuleId(moduleId)
|
||||
setSelectedLessonId(lessonId)
|
||||
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 => {
|
||||
@@ -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>
|
||||
<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 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">
|
||||
<BookOpen className="w-4 h-4" />
|
||||
<span>{modules.length} modules</span>
|
||||
@@ -321,7 +383,7 @@ export default function CoursePage() {
|
||||
</div>
|
||||
<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" />
|
||||
<span>{course.students.toLocaleString()} students</span>
|
||||
<span>{Number(course.students || 0).toLocaleString()} students</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -41,6 +41,16 @@ type ActivityData = {
|
||||
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() {
|
||||
const { user, walletConnected, logout, authMethod } = useAuth()
|
||||
const router = useRouter()
|
||||
@@ -58,6 +68,7 @@ export default function DashboardPage() {
|
||||
const [isUploadingImage, setIsUploadingImage] = useState(false)
|
||||
const [showAllActivities, setShowAllActivities] = useState(false)
|
||||
const [recentActivity, setRecentActivity] = useState<ActivityData[]>([])
|
||||
const [certificates, setCertificates] = useState<CertificateItem[]>([])
|
||||
const [profileData, setProfileData] = useState({
|
||||
name: user?.name || '',
|
||||
bio: user?.bio || '',
|
||||
@@ -93,13 +104,13 @@ export default function DashboardPage() {
|
||||
const fetchRealStats = async () => {
|
||||
setIsLoadingStats(true)
|
||||
try {
|
||||
const [statsResponse, activityResponse] = await Promise.all([
|
||||
const [statsResult, activityResult] = await Promise.allSettled([
|
||||
api.get("/api/dashboard/comprehensive-stats"),
|
||||
api.get("/api/dashboard/recent-activity"),
|
||||
])
|
||||
|
||||
if (statsResponse.data.success && statsResponse.data.data) {
|
||||
const data = statsResponse.data.data
|
||||
if (statsResult.status === "fulfilled" && statsResult.value.data.success && statsResult.value.data.data) {
|
||||
const data = statsResult.value.data.data
|
||||
const streakData = data.streak_data || {}
|
||||
setStats({
|
||||
coursesCompleted: data.courses_completed || 0,
|
||||
@@ -113,12 +124,25 @@ export default function DashboardPage() {
|
||||
})
|
||||
}
|
||||
|
||||
if (activityResponse.data?.success && Array.isArray(activityResponse.data?.data)) {
|
||||
setRecentActivity(activityResponse.data.data)
|
||||
if (activityResult.status === "fulfilled" && activityResult.value.data?.success && Array.isArray(activityResult.value.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) {
|
||||
console.error("Failed to fetch dashboard stats:", error)
|
||||
// Keep default values if fetch fails
|
||||
toast.error("Failed to load dashboard data")
|
||||
} finally {
|
||||
setIsLoadingStats(false)
|
||||
@@ -878,6 +902,49 @@ export default function DashboardPage() {
|
||||
</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>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user