feat: institutional + support + training admin sections (backend + frontend)

Ship three fully-wired admin areas end-to-end with APIs, seeds, tests and docs.

Backend (new `encoach_lms_api` addon + existing addons):
- Institutional: academic years/terms, departments, admission registers & admissions,
  courses/batches, lessons, fees (terms + student fees + invoicing with income-account
  auto-wiring), gradebook (assignments/grades), library, facilities (encoach.asset),
  student leave, result templates + marksheets (incl. delete-with-cascade).
- Support: `encoach.ticket` model + CRUD/assignee routes; payment records derived
  from `op.student.fees.details` and `account.move`; platform settings backed by
  `encoach.code` and `ir.config_parameter` (packages + grading config).
- Training: `encoach.vocab.item` + `encoach.grammar.rule` (plus progress models)
  with CRUD, pagination, search/level filters, and upsert-style progress endpoints.
  Odoo 19 compatibility: `_sql_constraints` replaced with `@api.constrains`;
  `ValidationError`/`UserError` mapped to HTTP 400.

Frontend:
- Rewire institutional admin pages (Academic Year Manager, Admissions, Courses,
  Lessons, Fees, Gradebook, Library, Facilities, Student Leave, Marksheets,
  Taxonomy, Resources) to real APIs with React Query invalidation and dialogs.
- New typed services: `payments.service.ts`, `platformSettings.service.ts`,
  `training.service.ts`. Updated `fees/gradebook/lms/courseware/taxonomy/
  resources/student-progress/generation` services + related types.
- Rewrite `VocabularyPage`, `GrammarPage`, `PaymentRecordPage`, `SettingsPage`,
  `TicketsPage` to consume live data with search/filter/progress/CRUD flows.
- New shared components: `TaxonomyCascade`, `MaterialViewer`, `teacher/TeacherLibrary`.
- Favicons/branding assets and misc. UX polish across teacher/student pages.

Tooling & QA:
- Seeders: `seed_demo.py`, `seed_demo_data.py`, `seed_institutional.py` (idempotent,
  covers institutional + support + training fixtures incl. income-account wiring).
- API write-flow test suites: `test_write_flows.py` (institutional),
  `test_support_flows.py` (support), `test_training_flows.py` (training),
  `test_ai_full.py`. All suites pass end-to-end.
- Docs: add `docs/PROJECT_SUMMARY.md` with per-section scope, artifacts and QA.
- `.gitignore`: ignore `pgdata_bak_*/`, `frontend/.vite/`, `frontend/dist/`,
  `frontend/node_modules/`.

Made-with: Cursor
This commit is contained in:
Yamen Ahmad
2026-04-19 03:13:23 +04:00
parent 50f58dc995
commit 98b9837a54
141 changed files with 20235 additions and 1453 deletions

View File

@@ -5,33 +5,38 @@ import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { useAssignments } from "@/hooks/queries";
import { Upload } from "lucide-react";
import { useCourseAssignments } from "@/hooks/queries";
import { Upload, ClipboardList } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import AiWritingHelper from "@/components/ai/AiWritingHelper";
import AiTipBanner from "@/components/ai/AiTipBanner";
import type { CourseAssignment } from "@/types";
export default function StudentAssignments() {
const [submitOpen, setSubmitOpen] = useState(false);
const [selectedAssignment, setSelectedAssignment] = useState<string | null>(null);
const [selectedAssignment, setSelectedAssignment] = useState<number | null>(null);
const [draftText, setDraftText] = useState("");
const { toast } = useToast();
const { data: assignmentsData, isLoading } = useAssignments();
const assignments = assignmentsData?.items ?? [];
const { data: assignmentsData, isLoading } = useCourseAssignments();
const assignments: CourseAssignment[] = assignmentsData?.items ?? [];
if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
const handleSubmit = () => {
setSubmitOpen(false);
setSelectedAssignment(null);
toast({ title: "Assignment Submitted", description: "Your work has been submitted successfully." });
};
const statusFilter = (status: string) => assignments.filter(a => status === "all" ? true : a.status === status);
const stateVariant = (s: string) => s === "finish" ? "default" : s === "cancel" ? "destructive" : "secondary";
const stateLabel = (s: string) => s === "publish" ? "Active" : s === "finish" ? "Completed" : s === "cancel" ? "Cancelled" : "Draft";
const stateFilter = (state: string) => assignments.filter(a => state === "all" ? true : a.state === state);
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Assignments</h1>
<p className="text-muted-foreground">View and submit your assignments.</p>
<p className="text-muted-foreground">View and submit your course assignments.</p>
</div>
<AiTipBanner context="student-assignments" variant="recommendation" />
@@ -39,26 +44,33 @@ export default function StudentAssignments() {
<Tabs defaultValue="all">
<TabsList>
<TabsTrigger value="all">All ({assignments.length})</TabsTrigger>
<TabsTrigger value="pending">Pending ({statusFilter("pending").length})</TabsTrigger>
<TabsTrigger value="submitted">Submitted ({statusFilter("submitted").length})</TabsTrigger>
<TabsTrigger value="graded">Graded ({statusFilter("graded").length})</TabsTrigger>
<TabsTrigger value="publish">Active ({stateFilter("publish").length})</TabsTrigger>
<TabsTrigger value="finish">Completed ({stateFilter("finish").length})</TabsTrigger>
</TabsList>
{["all", "pending", "submitted", "graded", "overdue"].map(tab => (
{["all", "publish", "finish"].map(tab => (
<TabsContent key={tab} value={tab} className="mt-4 space-y-3">
{statusFilter(tab).map(a => (
{stateFilter(tab).length === 0 ? (
<div className="text-center py-8">
<ClipboardList className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
<p className="text-muted-foreground text-sm">No assignments found.</p>
</div>
) : stateFilter(tab).map(a => (
<Card key={a.id}>
<CardContent className="pt-4">
<div className="flex items-center justify-between">
<div className="min-w-0">
<p className="font-medium text-sm">{a.title}</p>
<p className="text-xs text-muted-foreground">{a.courseName} · Due: {a.dueDate}</p>
{a.grade !== undefined && <p className="text-xs font-medium text-primary mt-1">Grade: {a.grade}/{a.maxGrade}</p>}
{a.feedback && <p className="text-xs text-muted-foreground mt-0.5">"{a.feedback}"</p>}
<p className="font-medium text-sm">{a.name}</p>
<p className="text-xs text-muted-foreground">
{a.course_name} · Due: {a.submission_date}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
Marks: {a.marks} · {a.assignment_type_name}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Badge variant={a.status === "graded" ? "default" : a.status === "overdue" ? "destructive" : "secondary"}>{a.status}</Badge>
{a.status === "pending" && (
<Badge variant={stateVariant(a.state)}>{stateLabel(a.state)}</Badge>
{a.state === "publish" && (
<Button size="sm" onClick={() => { setSelectedAssignment(a.id); setSubmitOpen(true); }}>Submit</Button>
)}
</div>

View File

@@ -1,13 +1,15 @@
import { useState } from "react";
import { useParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { FileText, Video, Image, Link2, Music, Download, CheckCircle2, Loader2 } from "lucide-react";
import { FileText, Video, Image, Link2, Music, Download, CheckCircle2, Loader2, Eye } from "lucide-react";
import { useChapter, useChapterMaterials, useChapterProgress, useCompleteChapter, useMarkMaterialViewed } from "@/hooks/queries";
import { coursewareService } from "@/services/courseware.service";
import { useToast } from "@/hooks/use-toast";
import type { MaterialType } from "@/types/courseware";
import MaterialViewer from "@/components/MaterialViewer";
import type { ChapterMaterial, MaterialType } from "@/types/courseware";
const typeIcons: Record<MaterialType, React.ReactNode> = {
pdf: <FileText className="h-5 w-5" />,
@@ -29,6 +31,9 @@ export default function StudentChapterView() {
const completeChapter = useCompleteChapter();
const markViewed = useMarkMaterialViewed();
const [activeMaterial, setActiveMaterial] = useState<ChapterMaterial | null>(null);
const [viewerOpen, setViewerOpen] = useState(false);
const completionPct = progress ? Math.round((progress.materials_completed / Math.max(progress.materials_total, 1)) * 100) : 0;
const handleDownload = async (materialId: number, name: string) => {
@@ -46,14 +51,16 @@ export default function StudentChapterView() {
};
const handleMarkComplete = () => {
completeChapter.mutate(chId, {
completeChapter.mutate({ chapterId: chId, courseId: Number(courseId) }, {
onSuccess: () => toast({ title: "Chapter Completed!" }),
onError: () => toast({ title: "Error", description: "Failed to mark complete", variant: "destructive" }),
});
};
const handleOpenMaterial = (materialId: number) => {
markViewed.mutate({ id: materialId, chapterId: chId });
const handleOpenMaterial = (material: ChapterMaterial) => {
markViewed.mutate({ id: material.id, chapterId: chId });
setActiveMaterial(material);
setViewerOpen(true);
};
if (lc || lm || lp) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
@@ -95,7 +102,7 @@ export default function StudentChapterView() {
{materials
.sort((a, b) => a.sequence - b.sequence)
.map(m => (
<Card key={m.id} className="hover:shadow-md transition-shadow cursor-pointer" onClick={() => handleOpenMaterial(m.id)}>
<Card key={m.id} className="hover:shadow-md transition-shadow cursor-pointer" onClick={() => handleOpenMaterial(m)}>
<CardContent className="py-4">
<div className="flex items-start gap-3">
<div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0 text-primary">
@@ -103,13 +110,23 @@ export default function StudentChapterView() {
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{m.name}</p>
<Badge variant="outline" className="mt-1 text-xs">{m.type}</Badge>
<div className="flex items-center gap-2 mt-1">
<Badge variant="outline" className="text-xs">{m.type}</Badge>
</div>
{m.description && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-2">{m.description}</p>
)}
</div>
{m.allow_download && (
<Button variant="ghost" size="icon" className="shrink-0" onClick={(e) => { e.stopPropagation(); handleDownload(m.id, m.name); }}>
<Download className="h-4 w-4" />
<div className="flex flex-col gap-1 shrink-0">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => { e.stopPropagation(); handleOpenMaterial(m); }}>
<Eye className="h-4 w-4" />
</Button>
)}
{m.allow_download && (
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => { e.stopPropagation(); handleDownload(m.id, m.name); }}>
<Download className="h-4 w-4" />
</Button>
)}
</div>
</div>
</CardContent>
</Card>
@@ -121,6 +138,13 @@ export default function StudentChapterView() {
</div>
)}
</div>
<MaterialViewer
material={activeMaterial}
open={viewerOpen}
onOpenChange={setViewerOpen}
onDownload={handleDownload}
/>
</div>
);
}

View File

@@ -4,30 +4,26 @@ import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { useCourses, useAssignments, useAttendance, useGrades } from "@/hooks/queries";
import { ArrowLeft, CheckCircle, Circle, FileText, Video, HelpCircle } from "lucide-react";
const iconMap = { video: Video, reading: FileText, quiz: HelpCircle };
import { useCourse, useChapters, useGrades, useCourseCompletion } from "@/hooks/queries";
import { ArrowLeft, BookOpen, Lock, ChevronRight, Play, CheckCircle2, Trophy } from "lucide-react";
export default function StudentCourseDetail() {
const { id } = useParams();
const { data: coursesData, isLoading: lc } = useCourses();
const { data: assignmentsData, isLoading: la } = useAssignments();
const { data: attendanceData, isLoading: lat } = useAttendance();
const { data: gradesData, isLoading: lg } = useGrades();
const courses = coursesData?.items ?? [];
const assignments = assignmentsData?.items ?? [];
const attendanceRecords = attendanceData ?? [];
const courseId = Number(id);
const { data: course, isLoading: lc } = useCourse(courseId);
const { data: chapters = [], isLoading: lch } = useChapters(courseId);
const { data: gradesData, isLoading: lg } = useGrades({ course_id: courseId });
const { data: completion } = useCourseCompletion(courseId);
const gradeRecords = gradesData ?? [];
if (lc || la || lat || lg) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
const course = courses.find(c => c.id === id);
if (lc || lch || lg) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
if (!course) return <div className="p-8 text-center text-muted-foreground">Course not found.</div>;
const courseAssignments = assignments.filter(a => a.courseId === id);
const courseAttendance = attendanceRecords.filter(a => a.courseId === id);
const courseGrades = gradeRecords.filter(g => g.courseId === id);
const sortedChapters = [...chapters].sort((a, b) => a.sequence - b.sequence);
const completedChapters = completion?.chapters_completed ?? 0;
const progress = completion?.progress_percent ?? (chapters.length > 0 ? Math.round((completedChapters / chapters.length) * 100) : 0);
const isCompleted = completion?.status === "completed";
const postTestAvailable = completion?.post_test_available ?? false;
return (
<div className="space-y-6">
@@ -35,91 +31,116 @@ export default function StudentCourseDetail() {
<Button variant="ghost" size="icon" asChild><Link to="/student/courses"><ArrowLeft className="h-4 w-4" /></Link></Button>
<div>
<h1 className="text-2xl font-bold">{course.title}</h1>
<p className="text-muted-foreground">{course.instructor} · {course.code}</p>
<p className="text-muted-foreground">{course.code} · {chapters.length} chapters</p>
</div>
</div>
{isCompleted && (
<Card className="border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-800">
<CardContent className="pt-6 flex items-center justify-between">
<div className="flex items-center gap-3">
<Trophy className="h-8 w-8 text-green-600" />
<div>
<p className="font-semibold text-green-800 dark:text-green-200">Course Completed!</p>
<p className="text-sm text-green-600 dark:text-green-400">You've finished all {chapters.length} chapters.</p>
</div>
</div>
{postTestAvailable && (
<Button asChild>
<Link to={`/student/my-exams?course_id=${courseId}`}>Take Post-Test</Link>
</Button>
)}
</CardContent>
</Card>
)}
<Card>
<CardContent className="pt-6">
<div className="flex items-center justify-between mb-2">
<span className="text-sm text-muted-foreground">Overall Progress</span>
<span className="text-sm font-bold">{course.progress}%</span>
<span className="text-sm font-bold">{progress}%</span>
</div>
<Progress value={course.progress} className="h-3" />
<Progress value={progress} className="h-3" />
<p className="text-xs text-muted-foreground mt-2">{completedChapters} of {chapters.length} chapters completed</p>
</CardContent>
</Card>
<Tabs defaultValue="materials">
<Tabs defaultValue="chapters">
<TabsList>
<TabsTrigger value="materials">Materials</TabsTrigger>
<TabsTrigger value="assignments">Assignments ({courseAssignments.length})</TabsTrigger>
<TabsTrigger value="attendance">Attendance</TabsTrigger>
<TabsTrigger value="grades">Grades</TabsTrigger>
<TabsTrigger value="chapters">Chapters ({chapters.length})</TabsTrigger>
<TabsTrigger value="grades">Grades ({gradeRecords.length})</TabsTrigger>
<TabsTrigger value="about">About</TabsTrigger>
</TabsList>
<TabsContent value="materials" className="space-y-4 mt-4">
{course.modules.length === 0 ? (
<p className="text-muted-foreground text-sm py-8 text-center">No modules available yet.</p>
) : course.modules.map(mod => (
<Card key={mod.id}>
<CardHeader className="pb-2">
<CardTitle className="text-base">{mod.title}</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{mod.lessons.map(lesson => {
const Icon = iconMap[lesson.type];
return (
<div key={lesson.id} className="flex items-center gap-3 p-2 rounded hover:bg-muted/50">
{lesson.completed ? <CheckCircle className="h-4 w-4 text-success shrink-0" /> : <Circle className="h-4 w-4 text-muted-foreground shrink-0" />}
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-sm flex-1">{lesson.title}</span>
<span className="text-xs text-muted-foreground">{lesson.duration}</span>
</div>
);
})}
</CardContent>
</Card>
))}
</TabsContent>
<TabsContent value="assignments" className="mt-4 space-y-3">
{courseAssignments.map(a => (
<Card key={a.id}>
<CardContent className="pt-4 flex items-center justify-between">
<div>
<p className="font-medium text-sm">{a.title}</p>
<p className="text-xs text-muted-foreground">Due: {a.dueDate}</p>
</div>
<Badge variant={a.status === "graded" ? "default" : a.status === "overdue" ? "destructive" : "secondary"}>
{a.status}
</Badge>
</CardContent>
</Card>
))}
</TabsContent>
<TabsContent value="attendance" className="mt-4 space-y-3">
{courseAttendance.map(a => (
<div key={a.id} className="flex items-center justify-between p-3 rounded border">
<span className="text-sm">{a.date}</span>
<Badge variant={a.status === "present" ? "default" : a.status === "absent" ? "destructive" : "secondary"}>
{a.status}
</Badge>
<TabsContent value="chapters" className="space-y-3 mt-4">
{sortedChapters.length === 0 ? (
<div className="text-center py-12">
<BookOpen className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
<p className="text-muted-foreground text-sm">No chapters available yet.</p>
</div>
) : sortedChapters.map((ch, idx) => (
<Link
key={ch.id}
to={ch.is_unlocked ? `/student/courses/${courseId}/chapters/${ch.id}` : "#"}
className={ch.is_unlocked ? "" : "pointer-events-none"}
>
<Card className={`transition-shadow ${ch.is_unlocked ? "hover:shadow-md cursor-pointer" : "opacity-60"}`}>
<CardContent className="flex items-center gap-4 py-4">
<div className="flex items-center justify-center h-10 w-10 rounded-full bg-primary/10 text-primary font-bold text-sm shrink-0">
{idx + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-medium text-sm truncate">{ch.name}</p>
{!ch.is_unlocked && <Lock className="h-3 w-3 text-muted-foreground shrink-0" />}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{ch.material_count} materials
{ch.description ? ` · ${ch.description.slice(0, 60)}${ch.description.length > 60 ? "..." : ""}` : ""}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{ch.is_unlocked ? (
<Badge variant="secondary" className="text-xs">
<Play className="h-3 w-3 mr-1" /> Open
</Badge>
) : (
<Badge variant="outline" className="text-xs">Locked</Badge>
)}
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</div>
</CardContent>
</Card>
</Link>
))}
</TabsContent>
<TabsContent value="grades" className="mt-4 space-y-3">
{courseGrades.map(g => (
{gradeRecords.length === 0 ? (
<p className="text-muted-foreground text-sm text-center py-8">No grades yet for this course.</p>
) : gradeRecords.map(g => (
<div key={g.id} className="flex items-center justify-between p-3 rounded border">
<div>
<p className="text-sm font-medium">{g.assignmentTitle}</p>
<p className="text-sm font-medium">{g.assignment_title}</p>
<p className="text-xs text-muted-foreground">{g.date}</p>
</div>
<span className="font-bold text-primary">{g.grade}/{g.maxGrade}</span>
<span className="font-bold text-primary">{g.grade}/{g.max_grade}</span>
</div>
))}
</TabsContent>
<TabsContent value="about" className="mt-4">
<Card>
<CardHeader><CardTitle className="text-base">About this Course</CardTitle></CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">{course.description || "No description available."}</p>
<div className="grid grid-cols-2 gap-4 text-sm">
<div><span className="text-muted-foreground">Enrolled Students:</span> <span className="font-medium">{course.enrolled}</span></div>
<div><span className="text-muted-foreground">Max Capacity:</span> <span className="font-medium">{course.max_capacity}</span></div>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);

View File

@@ -1,18 +1,17 @@
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import { Link } from "react-router-dom";
import { useCourses } from "@/hooks/queries";
import { BookOpen, Users, Clock } from "lucide-react";
import { useMyEnrolledCourses } from "@/hooks/queries";
import { BookOpen, Users, Play } from "lucide-react";
import AiTipBanner from "@/components/ai/AiTipBanner";
export default function StudentCourses() {
const { data: coursesData, isLoading } = useCourses();
const courses = coursesData?.items ?? [];
const { data: enrolledData, isLoading } = useMyEnrolledCourses();
const myCourses = enrolledData?.items ?? [];
if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
const myCourses = courses.filter(c => ["c1", "c2", "c5", "c8"].includes(c.id));
return (
<div className="space-y-6">
<div>
@@ -22,37 +21,50 @@ export default function StudentCourses() {
<AiTipBanner context="student-courses" variant="recommendation" />
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{myCourses.map((c) => (
<Link to={`/student/courses/${c.id}`} key={c.id}>
<Card className="hover:shadow-md transition-shadow h-full">
<div className="h-2 rounded-t-lg bg-primary" />
<CardContent className="pt-5 space-y-4">
<div>
<div className="flex items-center justify-between mb-1">
<Badge variant="secondary" className="text-xs">{c.level}</Badge>
<Badge variant="outline" className="text-xs">{c.code}</Badge>
{myCourses.length === 0 ? (
<div className="text-center py-12">
<BookOpen className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-semibold">No Enrolled Courses</h3>
<p className="text-muted-foreground mt-1">You haven't been enrolled in any courses yet. Contact your administrator.</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{myCourses.map((c) => (
<Link to={`/student/courses/${c.id}`} key={c.id}>
<Card className="hover:shadow-md transition-shadow h-full">
<div className="h-2 rounded-t-lg bg-primary" />
<CardContent className="pt-5 space-y-4">
<div>
<div className="flex items-center justify-between mb-1">
<Badge variant="secondary" className="text-xs">
{c.progress === 100 ? "Completed" : c.progress > 0 ? "In Progress" : "Not Started"}
</Badge>
<Badge variant="outline" className="text-xs">{c.code}</Badge>
</div>
<h3 className="font-semibold mt-2">{c.title || c.name}</h3>
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">{c.description}</p>
</div>
<h3 className="font-semibold mt-2">{c.title}</h3>
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">{c.description}</p>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1"><BookOpen className="h-3 w-3" />{c.modules.length} modules</span>
<span className="flex items-center gap-1"><Users className="h-3 w-3" />{c.enrolled} students</span>
</div>
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-muted-foreground">Progress</span>
<span className="font-medium">{c.progress}%</span>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1"><BookOpen className="h-3 w-3" />{c.chapter_count} chapters</span>
<span className="flex items-center gap-1"><Users className="h-3 w-3" />{c.student_count} students</span>
</div>
<Progress value={c.progress} className="h-2" />
</div>
<p className="text-xs text-muted-foreground flex items-center gap-1"><Clock className="h-3 w-3" /> {c.instructor}</p>
</CardContent>
</Card>
</Link>
))}
</div>
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-muted-foreground">Progress</span>
<span className="font-medium">{c.progress}%</span>
</div>
<Progress value={c.progress} className="h-2" />
</div>
<Button variant="outline" className="w-full" size="sm">
<Play className="mr-2 h-3 w-3" />
{c.progress > 0 ? "Continue Learning" : "Start Learning"}
</Button>
</CardContent>
</Card>
</Link>
))}
</div>
)}
</div>
);
}

View File

@@ -2,35 +2,39 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { BookOpen, ClipboardList, BarChart3, Calendar, ArrowRight } from "lucide-react";
import { BookOpen, ClipboardList, BarChart3, Calendar, ArrowRight, Play } from "lucide-react";
import { Link } from "react-router-dom";
import { useCourses, useAssignments, useGrades } from "@/hooks/queries";
import { useMyEnrolledCourses, useGrades } from "@/hooks/queries";
import { useAuth } from "@/contexts/AuthContext";
import AiStudyCoach from "@/components/ai/AiStudyCoach";
import AiTipBanner from "@/components/ai/AiTipBanner";
export default function StudentDashboard() {
const { data: coursesData, isLoading: lc } = useCourses();
const { data: assignmentsData, isLoading: la } = useAssignments();
const { user } = useAuth();
const { data: enrolledData, isLoading: lc } = useMyEnrolledCourses();
const { data: gradesData, isLoading: lg } = useGrades();
const courses = coursesData?.items ?? [];
const assignments = assignmentsData?.items ?? [];
const myCourses = enrolledData?.items ?? [];
const gradeRecords = gradesData ?? [];
if (lc || la || lg) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
if (lc || lg) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;
const myCourses = courses.filter(c => ["c1", "c2", "c5", "c8"].includes(c.id));
const upcomingAssignments = assignments.filter(a => a.status === "pending").slice(0, 3);
const recentGrades = gradeRecords.slice(0, 3);
const avgProgress = myCourses.length > 0 ? Math.round(myCourses.reduce((s, c) => s + c.progress, 0) / myCourses.length) : 0;
const avgGrade = gradeRecords.length > 0
? Math.round(gradeRecords.reduce((s, g) => s + (g.grade / g.max_grade) * 100, 0) / gradeRecords.length)
: 0;
const firstName = user?.name?.split(" ")[0] || "Student";
const stats = [
{ label: "Enrolled Courses", value: String(myCourses.length), icon: BookOpen, color: "text-primary" },
{ label: "Pending Assignments", value: String(assignments.filter(a => a.status === "pending").length), icon: ClipboardList, color: "text-warning" },
{ label: "Average Grade", value: "78%", icon: BarChart3, color: "text-success" },
{ label: "Attendance Rate", value: "94%", icon: Calendar, color: "text-info" },
{ label: "Overall Progress", value: `${avgProgress}%`, icon: ClipboardList, color: "text-warning" },
{ label: "Average Grade", value: gradeRecords.length > 0 ? `${avgGrade}%` : "N/A", icon: BarChart3, color: "text-success" },
{ label: "Total Chapters", value: String(myCourses.reduce((s, c) => s + c.chapter_count, 0)), icon: Calendar, color: "text-info" },
];
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Welcome back, Sarah!</h1>
<h1 className="text-2xl font-bold">Welcome back, {firstName}!</h1>
<p className="text-muted-foreground">Here's an overview of your learning progress.</p>
</div>
@@ -61,12 +65,14 @@ export default function StudentDashboard() {
<Button variant="ghost" size="sm" asChild><Link to="/student/courses">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
</CardHeader>
<CardContent className="space-y-4">
{myCourses.map((c) => (
{myCourses.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No enrolled courses yet.</p>
) : myCourses.map((c) => (
<Link to={`/student/courses/${c.id}`} key={c.id} className="block">
<div className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors">
<div className="min-w-0">
<p className="font-medium text-sm truncate">{c.title}</p>
<p className="text-xs text-muted-foreground">{c.instructor}</p>
<p className="font-medium text-sm truncate">{c.title || c.name}</p>
<p className="text-xs text-muted-foreground">{c.chapter_count} chapters · {c.total_materials} materials</p>
</div>
<div className="flex items-center gap-3 shrink-0">
<div className="w-24"><Progress value={c.progress} className="h-2" /></div>
@@ -81,16 +87,20 @@ export default function StudentDashboard() {
<div className="space-y-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-lg">Upcoming Assignments</CardTitle>
<Button variant="ghost" size="sm" asChild><Link to="/student/assignments">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
<CardTitle className="text-lg">Quick Actions</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{upcomingAssignments.map((a) => (
<div key={a.id} className="flex items-center justify-between p-2 rounded border">
<div><p className="text-sm font-medium">{a.title}</p><p className="text-xs text-muted-foreground">{a.courseName}</p></div>
<Badge variant="outline" className="text-xs">{a.dueDate}</Badge>
</div>
{myCourses.slice(0, 3).map(c => (
<Link key={c.id} to={`/student/courses/${c.id}`} className="flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors">
<Play className="h-4 w-4 text-primary shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{c.progress > 0 ? "Continue" : "Start"} {c.title || c.name}</p>
<p className="text-xs text-muted-foreground">{c.completed_chapters}/{c.chapter_count} chapters done</p>
</div>
<Badge variant="outline">{c.progress}%</Badge>
</Link>
))}
{myCourses.length === 0 && <p className="text-sm text-muted-foreground text-center py-4">Enroll in a course to get started.</p>}
</CardContent>
</Card>
@@ -100,10 +110,12 @@ export default function StudentDashboard() {
<Button variant="ghost" size="sm" asChild><Link to="/student/grades">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
</CardHeader>
<CardContent className="space-y-3">
{recentGrades.map((g) => (
{recentGrades.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No grades yet.</p>
) : recentGrades.map((g) => (
<div key={g.id} className="flex items-center justify-between p-2 rounded border">
<div><p className="text-sm font-medium">{g.assignmentTitle}</p><p className="text-xs text-muted-foreground">{g.courseName}</p></div>
<span className="text-sm font-bold text-primary">{g.grade}/{g.maxGrade}</span>
<div><p className="text-sm font-medium">{g.assignment_title}</p><p className="text-xs text-muted-foreground">{g.course_name}</p></div>
<span className="text-sm font-bold text-primary">{g.grade}/{g.max_grade}</span>
</div>
))}
</CardContent>