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

@@ -8,11 +8,13 @@ import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Trash2, Loader2, FileText, Video, Image, Link2, Upload, Music } from "lucide-react";
import { useChapter, useChapterMaterials, useUploadMaterial, useDeleteMaterial } from "@/hooks/queries";
import { Plus, Trash2, Loader2, FileText, Video, Image, Link2, Upload, Music, Library, Search, CheckCircle2 } from "lucide-react";
import { useChapter, useChapterMaterials, useUploadMaterial, useDeleteMaterial, useCreateMaterialFromResource } from "@/hooks/queries";
import { coursewareService } from "@/services/courseware.service";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { resourcesService } from "@/services/resources.service";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import type { MaterialType } from "@/types/courseware";
@@ -35,15 +37,32 @@ export default function ChapterDetail() {
const { data: materials = [], isLoading: loadingMaterials } = useChapterMaterials(chId);
const uploadMaterial = useUploadMaterial();
const deleteMaterial = useDeleteMaterial();
const fromResource = useCreateMaterialFromResource();
const fileRef = useRef<HTMLInputElement>(null);
const [showUpload, setShowUpload] = useState(false);
const [dialogTab, setDialogTab] = useState<string>("library");
const [matName, setMatName] = useState("");
const [matType, setMatType] = useState<MaterialType>("pdf");
const [matUrl, setMatUrl] = useState("");
const [matFile, setMatFile] = useState<File | null>(null);
const [allowDownload, setAllowDownload] = useState(true);
const [libSearch, setLibSearch] = useState("");
const [libTypeFilter, setLibTypeFilter] = useState("all");
const [selectedResourceId, setSelectedResourceId] = useState<number | null>(null);
const { data: resourcesData, isLoading: loadingResources } = useQuery({
queryKey: ["resources", "list", { search: libSearch, resource_type: libTypeFilter === "all" ? undefined : libTypeFilter }],
queryFn: () => resourcesService.list({
search: libSearch || undefined,
resource_type: libTypeFilter === "all" ? undefined : libTypeFilter,
limit: 50,
}),
enabled: showUpload,
});
const libraryResources = resourcesData?.items ?? [];
const toggleDownload = useMutation({
mutationFn: ({ id, allow }: { id: number; allow: boolean }) =>
coursewareService.updateMaterial(id, { allow_download: allow }),
@@ -51,7 +70,11 @@ export default function ChapterDetail() {
onError: () => toast({ title: "Error", description: "Failed to update material", variant: "destructive" }),
});
const resetForm = () => { setMatName(""); setMatType("pdf"); setMatUrl(""); setMatFile(null); setAllowDownload(true); };
const resetForm = () => {
setMatName(""); setMatType("pdf"); setMatUrl(""); setMatFile(null);
setAllowDownload(true); setSelectedResourceId(null); setLibSearch("");
setLibTypeFilter("all"); setDialogTab("library");
};
const handleUpload = () => {
const formData = new FormData();
@@ -64,17 +87,28 @@ export default function ChapterDetail() {
uploadMaterial.mutate(
{ chapterId: chId, formData },
{
onSuccess: () => { toast({ title: "Material Uploaded" }); setShowUpload(false); resetForm(); },
onSuccess: () => { toast({ title: "Material uploaded" }); setShowUpload(false); resetForm(); },
onError: () => toast({ title: "Error", description: "Failed to upload material", variant: "destructive" }),
},
);
};
const handleAddFromLibrary = () => {
if (!selectedResourceId) return;
fromResource.mutate(
{ chapterId: chId, resourceId: selectedResourceId },
{
onSuccess: () => { toast({ title: "Material added from library" }); setShowUpload(false); resetForm(); },
onError: () => toast({ title: "Error", description: "Failed to add material from library", variant: "destructive" }),
},
);
};
const handleDelete = (id: number) => {
deleteMaterial.mutate(
{ id, chapterId: chId },
{
onSuccess: () => toast({ title: "Material Deleted" }),
onSuccess: () => toast({ title: "Material deleted" }),
onError: () => toast({ title: "Error", description: "Failed to delete material", variant: "destructive" }),
},
);
@@ -105,49 +139,139 @@ export default function ChapterDetail() {
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold">Materials</h2>
<Dialog open={showUpload} onOpenChange={setShowUpload}>
<Dialog open={showUpload} onOpenChange={(open) => { setShowUpload(open); if (!open) resetForm(); }}>
<DialogTrigger asChild>
<Button size="sm"><Plus className="mr-2 h-4 w-4" /> Upload Material</Button>
<Button size="sm"><Plus className="mr-2 h-4 w-4" /> Add Material</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Upload Material</DialogTitle></DialogHeader>
<div className="space-y-4 pt-4">
<div className="space-y-2">
<Label>Name</Label>
<Input placeholder="Material name" value={matName} onChange={e => setMatName(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Type</Label>
<Select value={matType} onValueChange={v => setMatType(v as MaterialType)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="image">Image</SelectItem>
<SelectItem value="link">Link</SelectItem>
<SelectItem value="article">Article</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>File</Label>
<Input ref={fileRef} type="file" onChange={e => setMatFile(e.target.files?.[0] ?? null)} />
</div>
<div className="space-y-2">
<Label>Or URL</Label>
<Input placeholder="https://..." value={matUrl} onChange={e => setMatUrl(e.target.value)} />
</div>
<div className="flex items-center gap-2">
<Checkbox id="allow-dl" checked={allowDownload} onCheckedChange={v => setAllowDownload(!!v)} />
<Label htmlFor="allow-dl">Allow Download</Label>
</div>
<Button className="w-full" onClick={handleUpload} disabled={uploadMaterial.isPending || !matName}>
{uploadMaterial.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Upload className="mr-2 h-4 w-4" /> Upload
</Button>
</div>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader><DialogTitle>Add Material</DialogTitle></DialogHeader>
<Tabs value={dialogTab} onValueChange={setDialogTab} className="pt-2">
<TabsList className="w-full">
<TabsTrigger value="library" className="flex-1">
<Library className="mr-2 h-4 w-4" /> From Library
</TabsTrigger>
<TabsTrigger value="upload" className="flex-1">
<Upload className="mr-2 h-4 w-4" /> Upload Manual
</TabsTrigger>
</TabsList>
{/* Tab: From Library */}
<TabsContent value="library" className="space-y-4 pt-2">
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search resources…"
value={libSearch}
onChange={e => setLibSearch(e.target.value)}
className="pl-9"
/>
</div>
<Select value={libTypeFilter} onValueChange={setLibTypeFilter}>
<SelectTrigger className="w-[120px]"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="all">All Types</SelectItem>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="link">Link</SelectItem>
</SelectContent>
</Select>
</div>
<div className="max-h-[300px] overflow-y-auto border rounded-md">
{loadingResources ? (
<div className="flex justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : libraryResources.length === 0 ? (
<div className="text-center py-8 text-muted-foreground text-sm">
No resources found. Try a different search or upload manually.
</div>
) : (
<div className="divide-y">
{libraryResources.map(r => {
const selected = selectedResourceId === r.id;
return (
<button
key={r.id}
type="button"
onClick={() => setSelectedResourceId(selected ? null : r.id)}
className={`w-full text-left px-4 py-3 flex items-center gap-3 transition-colors hover:bg-muted/50 ${
selected ? "bg-primary/10 ring-1 ring-primary/30" : ""
}`}
>
<div className="shrink-0">
{selected ? (
<CheckCircle2 className="h-5 w-5 text-primary" />
) : (
typeIcons[r.resource_type as MaterialType] ?? <FileText className="h-5 w-5 text-muted-foreground" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{r.name}</p>
<p className="text-xs text-muted-foreground">
{r.resource_type} {r.topic_names?.length ? `· ${r.topic_names.slice(0, 2).join(", ")}` : ""}
</p>
</div>
<Badge variant="outline" className="capitalize shrink-0">{r.resource_type}</Badge>
</button>
);
})}
</div>
)}
</div>
<Button
className="w-full"
onClick={handleAddFromLibrary}
disabled={!selectedResourceId || fromResource.isPending}
>
{fromResource.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Library className="mr-2 h-4 w-4" />
Add Selected Resource
</Button>
</TabsContent>
{/* Tab: Manual Upload */}
<TabsContent value="upload" className="space-y-4 pt-2">
<div className="space-y-2">
<Label>Name</Label>
<Input placeholder="Material name" value={matName} onChange={e => setMatName(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Type</Label>
<Select value={matType} onValueChange={v => setMatType(v as MaterialType)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="image">Image</SelectItem>
<SelectItem value="link">Link</SelectItem>
<SelectItem value="article">Article</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>File</Label>
<Input ref={fileRef} type="file" onChange={e => setMatFile(e.target.files?.[0] ?? null)} />
</div>
<div className="space-y-2">
<Label>Or URL</Label>
<Input placeholder="https://..." value={matUrl} onChange={e => setMatUrl(e.target.value)} />
</div>
<div className="flex items-center gap-2">
<Checkbox id="allow-dl" checked={allowDownload} onCheckedChange={v => setAllowDownload(!!v)} />
<Label htmlFor="allow-dl">Allow Download</Label>
</div>
<Button className="w-full" onClick={handleUpload} disabled={uploadMaterial.isPending || !matName}>
{uploadMaterial.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Upload className="mr-2 h-4 w-4" /> Upload
</Button>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</div>
@@ -189,7 +313,7 @@ export default function ChapterDetail() {
))}
{materials.length === 0 && (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground py-8">No materials uploaded yet.</TableCell>
<TableCell colSpan={5} className="text-center text-muted-foreground py-8">No materials added yet.</TableCell>
</TableRow>
)}
</TableBody>

View File

@@ -1,23 +1,28 @@
import { useState } from "react";
import { useParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useParams, useNavigate } from "react-router-dom";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, GripVertical, Lock, Unlock, Trash2, Loader2, BookOpen } from "lucide-react";
import { useChapters, useCreateChapter, useDeleteChapter, useUnlockChapter, useLockChapter } from "@/hooks/queries";
import { Plus, GripVertical, Lock, Unlock, Trash2, Loader2, BookOpen, Target } from "lucide-react";
import { useChapters, useCreateChapter, useDeleteChapter, useUnlockChapter, useLockChapter, useCourse } from "@/hooks/queries";
import { useQuery } from "@tanstack/react-query";
import { taxonomyService, lmsService } from "@/services";
import { useToast } from "@/hooks/use-toast";
import type { ChapterUnlockMode } from "@/types/courseware";
export default function CourseChapters() {
const { courseId } = useParams<{ courseId: string }>();
const cid = Number(courseId);
const navigate = useNavigate();
const { toast } = useToast();
const { data: chapters = [], isLoading } = useChapters(cid);
const { data: course } = useCourse(cid);
const createChapter = useCreateChapter();
const deleteChapter = useDeleteChapter();
const unlockChapter = useUnlockChapter();
@@ -28,12 +33,45 @@ export default function CourseChapters() {
const [description, setDescription] = useState("");
const [startDate, setStartDate] = useState("");
const [unlockMode, setUnlockMode] = useState<ChapterUnlockMode>("manual");
const [topicId, setTopicId] = useState<number | null>(null);
const [selectedObjectiveIds, setSelectedObjectiveIds] = useState<number[]>([]);
const resetForm = () => { setName(""); setDescription(""); setStartDate(""); setUnlockMode("manual"); };
const subjectId = course?.encoach_subject_id;
const { data: topics = [] } = useQuery({
queryKey: ["taxonomy", "topics", subjectId],
queryFn: () => subjectId ? taxonomyService.listTopics({ subject_id: subjectId }) : Promise.resolve([]),
enabled: !!subjectId,
});
const { data: objectivesData } = useQuery({
queryKey: ["lms", "objectives", topicId],
queryFn: () => topicId ? lmsService.listLearningObjectives({ topic_id: topicId }) : Promise.resolve({ items: [], total: 0 }),
enabled: !!topicId,
});
const objectives = objectivesData?.items ?? [];
const selectedTopic = topics.find((t) => t.id === topicId);
const resetForm = () => {
setName(""); setDescription(""); setStartDate(""); setUnlockMode("manual");
setTopicId(null); setSelectedObjectiveIds([]);
};
const handleCreate = () => {
createChapter.mutate(
{ courseId: cid, data: { name, course_id: cid, description, start_date: startDate || undefined, unlock_mode: unlockMode } },
{
courseId: cid,
data: {
name,
course_id: cid,
description,
start_date: startDate || undefined,
unlock_mode: unlockMode,
topic_id: topicId ?? undefined,
learning_objective_ids: selectedObjectiveIds.length > 0 ? selectedObjectiveIds : undefined,
},
},
{
onSuccess: () => { toast({ title: "Chapter Created" }); setShowAdd(false); resetForm(); },
onError: () => toast({ title: "Error", description: "Failed to create chapter", variant: "destructive" }),
@@ -75,7 +113,7 @@ export default function CourseChapters() {
<DialogTrigger asChild>
<Button><Plus className="mr-2 h-4 w-4" /> Add Chapter</Button>
</DialogTrigger>
<DialogContent>
<DialogContent className="sm:max-w-[520px] max-h-[85vh] overflow-y-auto">
<DialogHeader><DialogTitle>Add New Chapter</DialogTitle></DialogHeader>
<div className="space-y-4 pt-4">
<div className="space-y-2">
@@ -86,21 +124,81 @@ export default function CourseChapters() {
<Label>Description</Label>
<Textarea placeholder="Brief description" value={description} onChange={e => setDescription(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Start Date</Label>
<Input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Unlock Mode</Label>
<Select value={unlockMode} onValueChange={v => setUnlockMode(v as ChapterUnlockMode)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="manual">Manual</SelectItem>
<SelectItem value="auto_date">Auto (Date)</SelectItem>
<SelectItem value="prerequisite">Prerequisite</SelectItem>
</SelectContent>
</Select>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Start Date</Label>
<Input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Unlock Mode</Label>
<Select value={unlockMode} onValueChange={v => setUnlockMode(v as ChapterUnlockMode)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="manual">Manual</SelectItem>
<SelectItem value="auto_date">Auto (Date)</SelectItem>
<SelectItem value="prerequisite">Prerequisite</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{topics.length > 0 && (
<div className="space-y-2">
<Label>Topic</Label>
<Select
value={topicId ? String(topicId) : "none"}
onValueChange={(v) => {
setTopicId(v === "none" ? null : Number(v));
setSelectedObjectiveIds([]);
}}
>
<SelectTrigger><SelectValue placeholder="Select topic..." /></SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{topics.map((t) => (
<SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>
))}
</SelectContent>
</Select>
{selectedTopic && (
<p className="text-xs text-muted-foreground">
Domain: <strong>{selectedTopic.domain_name}</strong>
</p>
)}
</div>
)}
{topicId && objectives.length > 0 && (
<div className="space-y-2">
<Label>
<Target className="inline h-3.5 w-3.5 mr-1" />
Learning Objectives ({selectedObjectiveIds.length} selected)
</Label>
<div className="border rounded-md p-3 max-h-[140px] overflow-y-auto space-y-1">
{objectives.map((o) => (
<label key={o.id} className="flex items-center gap-2 text-sm cursor-pointer hover:bg-muted/50 p-1 rounded">
<Checkbox
checked={selectedObjectiveIds.includes(o.id)}
onCheckedChange={() =>
setSelectedObjectiveIds((prev) =>
prev.includes(o.id)
? prev.filter((x) => x !== o.id)
: [...prev, o.id]
)
}
/>
<span className="flex-1">{o.name}</span>
{o.bloom_level && (
<Badge variant="outline" className="text-[10px] capitalize">
{o.bloom_level}
</Badge>
)}
</label>
))}
</div>
</div>
)}
<Button className="w-full" onClick={handleCreate} disabled={createChapter.isPending || !name}>
{createChapter.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create Chapter
@@ -114,17 +212,29 @@ export default function CourseChapters() {
{chapters
.sort((a, b) => a.sequence - b.sequence)
.map(ch => (
<Card key={ch.id} className="hover:shadow-sm transition-shadow">
<Card key={ch.id} className="hover:shadow-sm transition-shadow cursor-pointer" onClick={() => navigate(`/teacher/courses/${cid}/chapters/${ch.id}`)}>
<CardContent className="flex items-center gap-4 py-4">
<GripVertical className="h-5 w-5 text-muted-foreground shrink-0 cursor-grab" />
<GripVertical className="h-5 w-5 text-muted-foreground shrink-0 cursor-grab" onClick={e => e.stopPropagation()} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<BookOpen className="h-4 w-4 text-primary shrink-0" />
<span className="font-medium truncate">{ch.name}</span>
{ch.topic_name && (
<Badge variant="outline" className="text-[10px] shrink-0">{ch.topic_name}</Badge>
)}
{ch.domain_name && (
<span className="text-[10px] text-muted-foreground shrink-0">({ch.domain_name})</span>
)}
</div>
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
{ch.start_date && <span>{new Date(ch.start_date).toLocaleDateString()}</span>}
<span>{ch.material_count} material{ch.material_count !== 1 ? "s" : ""}</span>
{(ch.learning_objective_ids?.length ?? 0) > 0 && (
<span className="flex items-center gap-0.5">
<Target className="h-3 w-3" />
{ch.learning_objective_ids?.length} objective{(ch.learning_objective_ids?.length ?? 0) !== 1 ? "s" : ""}
</span>
)}
</div>
</div>
<Badge variant={ch.is_unlocked ? "default" : "secondary"}>
@@ -133,7 +243,7 @@ export default function CourseChapters() {
<Button
variant="ghost"
size="icon"
onClick={() => handleToggleLock(ch.id, ch.is_unlocked)}
onClick={(e) => { e.stopPropagation(); handleToggleLock(ch.id, ch.is_unlocked); }}
disabled={unlockChapter.isPending || lockChapter.isPending}
>
{ch.is_unlocked ? <Lock className="h-4 w-4" /> : <Unlock className="h-4 w-4" />}
@@ -141,7 +251,7 @@ export default function CourseChapters() {
<Button
variant="ghost"
size="icon"
onClick={() => handleDelete(ch.id)}
onClick={(e) => { e.stopPropagation(); handleDelete(ch.id); }}
disabled={deleteChapter.isPending}
>
<Trash2 className="h-4 w-4 text-destructive" />

View File

@@ -1,22 +1,22 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { useAssignments } from "@/hooks/queries";
import { Link } from "react-router-dom";
import { useCourseAssignments } from "@/hooks/queries";
import { ClipboardList } from "lucide-react";
import AiCreationAssistant from "@/components/ai/AiCreationAssistant";
import AiGeneratorModal from "@/components/ai/AiGeneratorModal";
import AiTipBanner from "@/components/ai/AiTipBanner";
import type { CourseAssignment } from "@/types";
export default function TeacherAssignments() {
const { data: assignmentsData, isLoading } = useAssignments();
const assignments = assignmentsData?.items ?? [];
const submissions: unknown[] = [];
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 teacherAssignments = assignments;
const pendingSubs = (submissions as { id: string; studentName: string; submittedAt: string; status: string; feedback?: string; grade?: number }[]).filter(s => s.status === "pending");
const gradedSubs = (submissions as { id: string; studentName: string; submittedAt: string; status: string; feedback?: string; grade?: number }[]).filter(s => s.status === "graded");
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">
@@ -35,48 +35,40 @@ export default function TeacherAssignments() {
<Tabs defaultValue="all">
<TabsList>
<TabsTrigger value="all">All ({teacherAssignments.length})</TabsTrigger>
<TabsTrigger value="pending">Pending Review ({pendingSubs.length})</TabsTrigger>
<TabsTrigger value="graded">Graded ({gradedSubs.length})</TabsTrigger>
<TabsTrigger value="all">All ({assignments.length})</TabsTrigger>
<TabsTrigger value="publish">Active ({stateFilter("publish").length})</TabsTrigger>
<TabsTrigger value="finish">Completed ({stateFilter("finish").length})</TabsTrigger>
<TabsTrigger value="draft">Drafts ({stateFilter("draft").length})</TabsTrigger>
</TabsList>
<TabsContent value="all" className="mt-4 space-y-3">
{teacherAssignments.map(a => (
<Link to={`/teacher/assignments/${a.id}`} key={a.id}>
<Card className="hover:bg-muted/30 transition-colors">
{["all", "publish", "finish", "draft"].map(tab => (
<TabsContent key={tab} value={tab} className="mt-4 space-y-3">
{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} className="hover:bg-muted/30 transition-colors">
<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">{a.entity_name} · Due: {a.end_date}</p></div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="capitalize text-xs">{a.state}</Badge>
<Badge variant={a.completed_count >= a.assignee_count && a.assignee_count > 0 ? "default" : "secondary"} className="capitalize">{a.state}</Badge>
<div className="min-w-0">
<p className="font-medium text-sm">{a.name}</p>
<p className="text-xs text-muted-foreground">
{a.course_name} · {a.batch_name} · Due: {a.submission_date}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{a.submission_count}/{a.allocation_count} submissions · Marks: {a.marks}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Badge variant="outline" className="text-xs">{a.assignment_type_name}</Badge>
<Badge variant={stateVariant(a.state)}>{stateLabel(a.state)}</Badge>
</div>
</CardContent>
</Card>
</Link>
))}
</TabsContent>
<TabsContent value="pending" className="mt-4 space-y-3">
{pendingSubs.map(s => (
<Card key={s.id}>
<CardContent className="pt-4 flex items-center justify-between">
<div><p className="font-medium text-sm">{s.studentName}</p><p className="text-xs text-muted-foreground">Submitted: {s.submittedAt}</p></div>
<Badge variant="secondary">Pending</Badge>
</CardContent>
</Card>
))}
</TabsContent>
<TabsContent value="graded" className="mt-4 space-y-3">
{gradedSubs.map(s => (
<Card key={s.id}>
<CardContent className="pt-4 flex items-center justify-between">
<div><p className="font-medium text-sm">{s.studentName}</p><p className="text-xs text-muted-foreground">{s.feedback}</p></div>
<span className="font-bold text-primary">{s.grade}</span>
</CardContent>
</Card>
))}
</TabsContent>
))}
</TabsContent>
))}
</Tabs>
</div>
);

View File

@@ -1,16 +1,95 @@
import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useCourses } from "@/hooks/queries";
import { Link } from "react-router-dom";
import { Plus, Users, BookOpen, Archive } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { useCourses, useChapters } from "@/hooks/queries";
import { lmsService } from "@/services";
import { useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate } from "react-router-dom";
import { Plus, Users, BookOpen, Pencil, FolderOpen, Wand2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import type { Course } from "@/types";
function CourseCard({ course }: { course: Course }) {
const [editOpen, setEditOpen] = useState(false);
const [form, setForm] = useState({ title: course.title, code: course.code, description: course.description, max_capacity: course.max_capacity });
const { data: chapters = [] } = useChapters(course.id);
const qc = useQueryClient();
const { toast } = useToast();
const navigate = useNavigate();
const [saving, setSaving] = useState(false);
async function handleSave() {
setSaving(true);
try {
await lmsService.updateCourse(course.id, form);
qc.invalidateQueries({ queryKey: ["lms", "courses"] });
toast({ title: "Course updated" });
setEditOpen(false);
} catch (e: unknown) {
toast({ title: "Error", description: e instanceof Error ? e.message : String(e), variant: "destructive" });
} finally {
setSaving(false);
}
}
const totalMaterials = chapters.reduce((s, ch) => s + (ch.material_count || 0), 0);
return (
<>
<Card className="hover:shadow-md transition-shadow">
<div className="h-2 rounded-t-lg bg-primary" />
<CardContent className="pt-5 space-y-3">
<div className="flex items-center justify-between">
<Badge variant={course.status === "active" ? "default" : "secondary"} className="capitalize">{course.status}</Badge>
<span className="text-xs text-muted-foreground">{course.code}</span>
</div>
<h3 className="font-semibold">{course.title}</h3>
{course.description && <p className="text-sm text-muted-foreground line-clamp-2">{course.description}</p>}
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1"><Users className="h-3 w-3" />{course.enrolled} students</span>
<span className="flex items-center gap-1"><BookOpen className="h-3 w-3" />{chapters.length} chapters · {totalMaterials} materials</span>
</div>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" onClick={() => { setForm({ title: course.title, code: course.code, description: course.description, max_capacity: course.max_capacity }); setEditOpen(true); }}>
<Pencil className="mr-1.5 h-3 w-3" /> Edit
</Button>
<Button size="sm" variant="default" onClick={() => navigate(`/teacher/courses/${course.id}/chapters`)}>
<FolderOpen className="mr-1.5 h-3 w-3" /> Chapters & Materials
</Button>
<Button size="sm" variant="ghost" onClick={() => navigate(`/teacher/courses/${course.id}/workbench`)}>
<Wand2 className="mr-1.5 h-3 w-3" /> AI Workbench
</Button>
</div>
</CardContent>
</Card>
<Dialog open={editOpen} onOpenChange={setEditOpen}>
<DialogContent>
<DialogHeader><DialogTitle>Edit Course</DialogTitle></DialogHeader>
<div className="space-y-4 py-2">
<div><Label>Title *</Label><Input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} /></div>
<div><Label>Code</Label><Input value={form.code} onChange={e => setForm(f => ({ ...f, code: e.target.value }))} /></div>
<div><Label>Description</Label><Textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows={3} /></div>
<div><Label>Max Capacity</Label><Input type="number" value={form.max_capacity} onChange={e => setForm(f => ({ ...f, max_capacity: Number(e.target.value) || 30 }))} /></div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
<Button onClick={handleSave} disabled={saving}>{saving ? "Saving..." : "Save Changes"}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
export default function TeacherCourses() {
const { data: coursesData, isLoading } = useCourses();
const courses = coursesData?.items ?? [];
const teacherCourses = courses;
const { toast } = useToast();
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>;
@@ -24,29 +103,18 @@ export default function TeacherCourses() {
<Button asChild><Link to="/teacher/courses/new"><Plus className="mr-2 h-4 w-4" />New Course</Link></Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{teacherCourses.map(c => (
<Card key={c.id} className="hover:shadow-md transition-shadow">
<div className="h-2 rounded-t-lg bg-primary" />
<CardContent className="pt-5 space-y-3">
<div className="flex items-center justify-between">
<Badge variant={c.status === "active" ? "default" : "secondary"} className="capitalize">{c.status}</Badge>
<span className="text-xs text-muted-foreground">{c.code}</span>
</div>
<h3 className="font-semibold">{c.title}</h3>
<p className="text-sm text-muted-foreground line-clamp-2">{c.description}</p>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1"><Users className="h-3 w-3" />{c.enrolled} students</span>
<span className="flex items-center gap-1"><BookOpen className="h-3 w-3" />{c.modules.length} modules</span>
</div>
<div className="flex gap-2">
<Button size="sm" variant="outline" asChild><Link to={`/teacher/courses/${c.id}/edit`}>Edit</Link></Button>
<Button size="sm" variant="ghost" onClick={() => toast({ title: "Course archived" })}><Archive className="h-3 w-3" /></Button>
</div>
</CardContent>
</Card>
))}
</div>
{courses.length === 0 ? (
<div className="text-center py-16">
<BookOpen className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-semibold">No Courses Yet</h3>
<p className="text-muted-foreground mt-1">Create your first course to get started.</p>
<Button className="mt-4" asChild><Link to="/teacher/courses/new"><Plus className="mr-2 h-4 w-4" /> Create Course</Link></Button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{courses.map(c => <CourseCard key={c.id} course={c} />)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,515 @@
import { useState, useRef } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Search, Upload, FileText, Video, Link2, Download, Trash2,
CheckCircle2, Clock, XCircle, Loader2, BookOpen, Music, Image,
Library, Plus, CalendarDays, X,
} from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { resourcesService } from "@/services/resources.service";
import { coursewareService } from "@/services/courseware.service";
import { taxonomyService } from "@/services/taxonomy.service";
import { useToast } from "@/hooks/use-toast";
import { TaxonomyCascade } from "@/components/TaxonomyCascade";
import type { Resource, ResourceTag } from "@/types";
const statusBadge: Record<string, { variant: "default" | "secondary" | "destructive"; icon: React.ReactNode }> = {
approved: { variant: "default", icon: <CheckCircle2 className="h-3 w-3 mr-1" /> },
pending: { variant: "secondary", icon: <Clock className="h-3 w-3 mr-1" /> },
rejected: { variant: "destructive", icon: <XCircle className="h-3 w-3 mr-1" /> },
};
const typeIcons: Record<string, React.ReactNode> = {
pdf: <FileText className="h-4 w-4 text-red-500" />,
video: <Video className="h-4 w-4 text-blue-500" />,
link: <Link2 className="h-4 w-4 text-green-500" />,
document: <FileText className="h-4 w-4 text-orange-500" />,
interactive: <FileText className="h-4 w-4 text-purple-500" />,
article: <FileText className="h-4 w-4 text-indigo-500" />,
audio: <Music className="h-4 w-4 text-yellow-500" />,
image: <Image className="h-4 w-4 text-pink-500" />,
};
interface CourseMaterialItem {
id: number;
name: string;
type: string;
course_name: string;
chapter_name: string;
source: string;
file_url: string | null;
url: string | null;
description: string | null;
course_id: number;
}
export default function TeacherLibrary() {
const { toast } = useToast();
const qc = useQueryClient();
const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState("all");
const [subjectFilter, setSubjectFilter] = useState<string>("all");
const [tagFilter, setTagFilter] = useState<string>("all");
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [activeTab, setActiveTab] = useState("all");
const [showUpload, setShowUpload] = useState(false);
const [uploadType, setUploadType] = useState("pdf");
const [uploadSubjectId, setUploadSubjectId] = useState<string>("none");
const [uploadDomainId, setUploadDomainId] = useState<string>("none");
const [uploadTopicIds, setUploadTopicIds] = useState<number[]>([]);
const [uploadObjectiveIds, setUploadObjectiveIds] = useState<number[]>([]);
const [uploadTagIds, setUploadTagIds] = useState<number[]>([]);
const fileRef = useRef<HTMLInputElement>(null);
const { data: subjects } = useQuery({
queryKey: ["taxonomy", "subjects"],
queryFn: () => taxonomyService.listSubjects(),
});
const { data: tags } = useQuery({
queryKey: ["resource-tags"],
queryFn: () => resourcesService.listTags(),
});
const { data: resourcesData, isLoading: loadingResources } = useQuery({
queryKey: ["resources", "list", { search, resource_type: typeFilter === "all" ? undefined : typeFilter, subject_id: subjectFilter === "all" ? undefined : subjectFilter, tag_id: tagFilter === "all" ? undefined : tagFilter, date_from: dateFrom || undefined, date_to: dateTo || undefined }],
queryFn: () => resourcesService.list({
search: search || undefined,
resource_type: typeFilter === "all" ? undefined : typeFilter,
subject_id: subjectFilter === "all" ? undefined : Number(subjectFilter),
tag_id: tagFilter === "all" ? undefined : Number(tagFilter),
date_from: dateFrom || undefined,
date_to: dateTo || undefined,
}),
});
const resources = resourcesData?.items ?? [];
const { data: materialsData, isLoading: loadingMaterials } = useQuery({
queryKey: ["materials", "search", { search, type: typeFilter }],
queryFn: () => coursewareService.searchMaterials({
search: search || undefined,
type: typeFilter === "all" ? undefined : typeFilter,
}),
});
const courseMaterials = materialsData?.items ?? [];
const uploadMutation = useMutation({
mutationFn: (formData: FormData) => resourcesService.upload(formData),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["resources"] });
toast({ title: "Resource uploaded successfully" });
setShowUpload(false);
setUploadTagIds([]);
setUploadSubjectId("none");
setUploadDomainId("none");
setUploadTopicIds([]);
setUploadObjectiveIds([]);
},
onError: () => toast({ title: "Error", description: "Upload failed", variant: "destructive" }),
});
const deleteMutation = useMutation({
mutationFn: (id: number) => resourcesService.delete(id),
onSuccess: () => { qc.invalidateQueries({ queryKey: ["resources"] }); toast({ title: "Resource deleted" }); },
onError: () => toast({ title: "Error", description: "Delete failed", variant: "destructive" }),
});
const handleUpload = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
if (uploadTagIds.length > 0) formData.set("tag_ids", uploadTagIds.join(","));
if (uploadDomainId !== "none") formData.set("domain_id", uploadDomainId);
if (uploadTopicIds.length > 0) formData.set("topic_ids", uploadTopicIds.join(","));
if (uploadObjectiveIds.length > 0) formData.set("learning_objective_ids", uploadObjectiveIds.join(","));
uploadMutation.mutate(formData);
};
const toggleUploadTag = (id: number) => {
setUploadTagIds((prev) => prev.includes(id) ? prev.filter((t) => t !== id) : [...prev, id]);
};
const clearFilters = () => {
setSearch(""); setTypeFilter("all"); setSubjectFilter("all");
setTagFilter("all"); setDateFrom(""); setDateTo("");
};
const hasActiveFilters = search || typeFilter !== "all" || subjectFilter !== "all" || tagFilter !== "all" || dateFrom || dateTo;
const isLoading = loadingResources || loadingMaterials;
const formatDate = (iso?: string) => {
if (!iso) return "";
try { return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); } catch { return ""; }
};
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Library className="h-6 w-6" /> Resource Library
</h1>
<p className="text-muted-foreground">Browse shared resources and your course materials. Upload new content or pick existing resources when building courses.</p>
</div>
<Button onClick={() => setShowUpload(true)}>
<Upload className="mr-2 h-4 w-4" /> Upload Resource
</Button>
</div>
{/* Stats */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("all")}>
<CardContent className="pt-6 flex items-center gap-4">
<div className="p-3 rounded-full bg-primary/10"><Library className="h-5 w-5 text-primary" /></div>
<div>
<p className="text-2xl font-bold">{resources.length + courseMaterials.length}</p>
<p className="text-sm text-muted-foreground">Total Resources</p>
</div>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("library")}>
<CardContent className="pt-6 flex items-center gap-4">
<div className="p-3 rounded-full bg-blue-500/10"><FileText className="h-5 w-5 text-blue-500" /></div>
<div>
<p className="text-2xl font-bold">{resources.length}</p>
<p className="text-sm text-muted-foreground">Shared Library</p>
</div>
</CardContent>
</Card>
<Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setActiveTab("materials")}>
<CardContent className="pt-6 flex items-center gap-4">
<div className="p-3 rounded-full bg-green-500/10"><BookOpen className="h-5 w-5 text-green-500" /></div>
<div>
<p className="text-2xl font-bold">{courseMaterials.length}</p>
<p className="text-sm text-muted-foreground">Course Materials</p>
</div>
</CardContent>
</Card>
</div>
{/* Filters + Table */}
<Card>
<CardHeader className="space-y-3">
<div className="flex items-center gap-3 flex-wrap">
<div className="relative flex-1 min-w-[200px]">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input placeholder="Search resources…" value={search} onChange={e => setSearch(e.target.value)} className="pl-9" />
</div>
<Select value={subjectFilter} onValueChange={setSubjectFilter}>
<SelectTrigger className="w-[150px]"><SelectValue placeholder="Subject" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">All Subjects</SelectItem>
{(subjects ?? []).map((s) => (
<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>
))}
</SelectContent>
</Select>
<Select value={tagFilter} onValueChange={setTagFilter}>
<SelectTrigger className="w-[140px]"><SelectValue placeholder="Tag" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">All Tags</SelectItem>
{(tags ?? []).map((t) => (
<SelectItem key={t.id} value={String(t.id)}>
<span className="flex items-center gap-2">
<span className="h-2 w-2 rounded-full inline-block" style={{ backgroundColor: t.color }} />
{t.name}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={typeFilter} onValueChange={setTypeFilter}>
<SelectTrigger className="w-[130px]"><SelectValue placeholder="Type" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">All Types</SelectItem>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="link">Link</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="article">Article</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="image">Image</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<CalendarDays className="h-4 w-4" />
<span>From</span>
<Input type="date" value={dateFrom} onChange={e => setDateFrom(e.target.value)} className="w-[150px] h-8 text-xs" />
<span>To</span>
<Input type="date" value={dateTo} onChange={e => setDateTo(e.target.value)} className="w-[150px] h-8 text-xs" />
</div>
{hasActiveFilters && (
<Button variant="ghost" size="sm" onClick={clearFilters} className="text-muted-foreground">
<X className="h-3 w-3 mr-1" /> Clear filters
</Button>
)}
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex justify-center py-12"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>
) : (
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="mb-4">
<TabsTrigger value="all">All ({resources.length + courseMaterials.length})</TabsTrigger>
<TabsTrigger value="library">Shared Library ({resources.length})</TabsTrigger>
<TabsTrigger value="materials">Course Materials ({courseMaterials.length})</TabsTrigger>
</TabsList>
<TabsContent value="all">
<ResourceTable resources={resources} materials={courseMaterials} showSource onDelete={(id) => { if (window.confirm("Delete?")) deleteMutation.mutate(id); }} deletePending={deleteMutation.isPending} toast={toast} formatDate={formatDate} />
</TabsContent>
<TabsContent value="library">
<ResourceTable resources={resources} materials={[]} onDelete={(id) => { if (window.confirm("Delete?")) deleteMutation.mutate(id); }} deletePending={deleteMutation.isPending} toast={toast} formatDate={formatDate} />
</TabsContent>
<TabsContent value="materials">
<ResourceTable resources={[]} materials={courseMaterials} showCourseInfo onDelete={() => {}} deletePending={false} toast={toast} formatDate={formatDate} />
</TabsContent>
</Tabs>
)}
</CardContent>
</Card>
{/* Upload Dialog */}
<Dialog open={showUpload} onOpenChange={(o) => { setShowUpload(o); if (!o) { setUploadTagIds([]); setUploadSubjectId("none"); setUploadDomainId("none"); setUploadTopicIds([]); setUploadObjectiveIds([]); } }}>
<DialogContent className="sm:max-w-[540px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2"><Plus className="h-5 w-5" /> Upload New Resource</DialogTitle>
</DialogHeader>
<form onSubmit={handleUpload} className="space-y-4 pt-2">
<input type="hidden" name="resource_type" value={uploadType} />
{uploadSubjectId !== "none" && <input type="hidden" name="subject_id" value={uploadSubjectId} />}
<div className="space-y-2"><Label>Name *</Label><Input name="name" placeholder="Resource title" required /></div>
<div className="space-y-2">
<Label>Type</Label>
<Select value={uploadType} onValueChange={setUploadType}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="link">Link / URL</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="image">Image</SelectItem>
</SelectContent>
</Select>
</div>
<TaxonomyCascade
subjectId={uploadSubjectId} onSubjectChange={setUploadSubjectId}
domainId={uploadDomainId} onDomainChange={setUploadDomainId}
topicIds={uploadTopicIds} onTopicIdsChange={setUploadTopicIds}
objectiveIds={uploadObjectiveIds} onObjectiveIdsChange={setUploadObjectiveIds}
/>
<InlineTagPicker
allTags={tags ?? []}
selectedIds={uploadTagIds}
onToggle={toggleUploadTag}
onTagCreated={() => qc.invalidateQueries({ queryKey: ["resource-tags"] })}
/>
<div className="space-y-2"><Label>File</Label><Input name="file" type="file" ref={fileRef} /></div>
<DialogFooter>
<Button type="button" variant="ghost" onClick={() => setShowUpload(false)}>Cancel</Button>
<Button type="submit" disabled={uploadMutation.isPending}>
{uploadMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Upload
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</div>
);
}
function ResourceTable({
resources, materials, showSource, showCourseInfo, onDelete, deletePending, toast, formatDate,
}: {
resources: Resource[];
materials: CourseMaterialItem[];
showSource?: boolean;
showCourseInfo?: boolean;
onDelete: (id: number) => void;
deletePending: boolean;
toast: ReturnType<typeof useToast>["toast"];
formatDate: (iso?: string) => string;
}) {
type Row = {
key: string; name: string; type: string; source: "library" | "course";
context: string; tags?: { id: number; name: string; color: string }[];
status?: string; createdAt?: string; resourceId?: number;
};
const rows: Row[] = [
...resources.map((r): Row => ({
key: `r-${r.id}`, name: r.name, type: r.resource_type, source: "library",
context: [r.subject_name, ...(r.topic_names?.slice(0, 2) ?? [])].filter(Boolean).join(" ") || "",
tags: r.tags ?? [], status: r.review_status, createdAt: r.created_at, resourceId: r.id,
})),
...materials.map((m): Row => ({
key: `m-${m.id}`, name: m.name, type: m.type, source: "course",
context: showCourseInfo || showSource ? `${m.course_name} ${m.chapter_name}` : m.chapter_name || "",
})),
];
if (rows.length === 0) {
return (
<div className="text-center py-12 text-muted-foreground">
<Library className="h-12 w-12 mx-auto mb-3 opacity-40" />
<p className="font-medium">No resources found</p>
<p className="text-sm">Upload a resource or add materials to your courses.</p>
</div>
);
}
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Type</TableHead>
{showSource && <TableHead>Source</TableHead>}
<TableHead>Subject / Tags</TableHead>
<TableHead>Status</TableHead>
<TableHead>Uploaded</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row) => {
const sb = row.status ? (statusBadge[row.status] ?? statusBadge.pending) : null;
return (
<TableRow key={row.key}>
<TableCell>
<div className="flex items-center gap-2">
{typeIcons[row.type] ?? <FileText className="h-4 w-4" />}
<span className="font-medium">{row.name}</span>
</div>
</TableCell>
<TableCell><Badge variant="outline" className="capitalize">{row.type}</Badge></TableCell>
{showSource && (
<TableCell>
<Badge variant={row.source === "library" ? "secondary" : "default"} className="text-xs">
{row.source === "library" ? "Library" : <><BookOpen className="h-3 w-3 mr-1 inline" />Course</>}
</Badge>
</TableCell>
)}
<TableCell>
<div className="flex flex-col gap-1">
{row.context && <span className="text-xs text-muted-foreground">{row.context}</span>}
{row.tags && row.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{row.tags.map((t) => (
<span key={t.id} className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium text-white" style={{ backgroundColor: t.color }}>{t.name}</span>
))}
</div>
)}
{!row.context && (!row.tags || row.tags.length === 0) && <span className="text-muted-foreground"></span>}
</div>
</TableCell>
<TableCell>
{sb ? (
<Badge variant={sb.variant} className="flex items-center w-fit">{sb.icon}{row.status}</Badge>
) : (
<Badge variant="default" className="flex items-center w-fit"><CheckCircle2 className="h-3 w-3 mr-1" />indexed</Badge>
)}
</TableCell>
<TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatDate(row.createdAt)}</TableCell>
<TableCell className="text-right">
<div className="flex items-center justify-end gap-1">
{row.source === "library" && row.resourceId && (
<>
<Button variant="ghost" size="icon" title="Download" onClick={async () => {
try {
const blob = await resourcesService.download(row.resourceId!);
const url = URL.createObjectURL(blob); const a = document.createElement("a");
a.href = url; a.download = row.name || "resource"; a.click(); URL.revokeObjectURL(url);
} catch { toast({ title: "Download failed", variant: "destructive" }); }
}}>
<Download className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" title="Delete" onClick={() => onDelete(row.resourceId!)} disabled={deletePending}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</>
)}
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
);
}
const INLINE_TAG_COLORS = ["#3b82f6", "#ef4444", "#22c55e", "#f59e0b", "#8b5cf6", "#ec4899", "#06b6d4"];
function InlineTagPicker({
allTags, selectedIds, onToggle, onTagCreated,
}: {
allTags: ResourceTag[];
selectedIds: number[];
onToggle: (id: number) => void;
onTagCreated: (tag: ResourceTag) => void;
}) {
const [newName, setNewName] = useState("");
const [creating, setCreating] = useState(false);
const handleCreate = async () => {
const name = newName.trim();
if (!name) return;
setCreating(true);
try {
const color = INLINE_TAG_COLORS[Math.floor(Math.random() * INLINE_TAG_COLORS.length)];
const tag = await resourcesService.createTag({ name, color });
onTagCreated(tag);
onToggle(tag.id);
setNewName("");
} catch { /* ignore */ }
setCreating(false);
};
return (
<div className="space-y-2">
<Label>Tags</Label>
<div className="flex flex-wrap gap-2">
{allTags.map((t) => (
<Badge
key={t.id}
variant={selectedIds.includes(t.id) ? "default" : "outline"}
className="cursor-pointer select-none transition-colors"
style={selectedIds.includes(t.id) ? { backgroundColor: t.color, borderColor: t.color, color: "#fff" } : { borderColor: t.color, color: t.color }}
onClick={() => onToggle(t.id)}
>
{t.name}
</Badge>
))}
</div>
<div className="flex gap-2 items-center">
<Input
placeholder="New tag…"
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); handleCreate(); } }}
className="h-8 text-sm flex-1"
/>
<Button type="button" size="sm" variant="outline" disabled={!newName.trim() || creating} onClick={handleCreate}>
{creating ? <Loader2 className="h-3 w-3 animate-spin" /> : <><Plus className="h-3 w-3 mr-1" />Add</>}
</Button>
</div>
</div>
);
}