feat: Generation Page AI workflows + AI/Vector modules + exam session fixes

Generation Page (complete rebuild):
- Full production-parity exam generation wizard with 4 IELTS modules
- Reading: AI passage gen, 5 exercise types (MCQ, Fill, Write, T/F, Match)
- Listening: 4 section types, AI context gen, TTS audio gen (ElevenLabs)
- Writing: Task 1/2, AI instruction gen, word limits, marks
- Speaking: 3 parts, AI script gen, avatar video gen (7 avatars)
- Per-module config: timer, CEFR difficulty, access, approval, rubrics
- Exam submission workflow (draft/published)

Exam Structures:
- New encoach.exam.structure model + CRUD controller
- ExamStructuresPage wired to real API

AI Module (encoach_ai):
- OpenAI service, ElevenLabs TTS, AWS Polly, ELAI avatars
- AI settings model with Odoo config parameters
- 7 generation endpoints (passage, exercises, instructions, scripts, context)

Vector Module (encoach_vector):
- pgvector integration for RAG-based content search
- Embedding service with sentence-transformers

Exam Session Fixes:
- Fixed ExamSession.tsx field mapping (question_type→type, exam_title→title)
- Fixed submit payload to include attempt_id and answers
- Fixed normalizeType to handle null/undefined

Tested: 12/12 API tests passed, browser-verified with real OpenAI calls
Made-with: Cursor
This commit is contained in:
Yamen Ahmad
2026-04-11 14:27:03 +04:00
parent 140ca7408d
commit b02ee8b6b7
64 changed files with 2639 additions and 264 deletions

View File

@@ -8,12 +8,13 @@ export default function AiAlertBanner() {
const [dismissedIds, setDismissedIds] = useState<Set<string>>(() => new Set());
const [errorDismissed, setErrorDismissed] = useState(false);
const { data: alerts, isLoading, isError, error } = useQuery({
const { data: resp, isLoading, isError, error } = useQuery({
queryKey: ["ai", "alerts"],
queryFn: () => analyticsService.getAlerts(),
});
const visible = alerts?.filter((a) => !dismissedIds.has(a.id)) ?? [];
const alerts = resp?.alerts ?? [];
const visible = alerts.filter((a, i) => !dismissedIds.has(String(i)));
if (isLoading) {
return (
@@ -43,7 +44,7 @@ export default function AiAlertBanner() {
if (isError && errorDismissed) return null;
if (!alerts?.length) {
if (!alerts.length) {
return (
<div className="rounded-lg border border-muted bg-muted/20 p-4 flex items-start gap-3">
<Sparkles className="h-5 w-5 text-muted-foreground shrink-0 mt-0.5" />
@@ -56,8 +57,8 @@ export default function AiAlertBanner() {
return (
<div className="space-y-3">
{visible.map((alert) => (
<div key={alert.id} className="rounded-lg border border-warning/30 bg-warning/10 p-4 flex items-start gap-3">
{visible.map((alert, idx) => (
<div key={idx} className="rounded-lg border border-warning/30 bg-warning/10 p-4 flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-warning shrink-0 mt-0.5" />
<div className="flex-1">
<p className="text-sm font-medium flex items-center gap-1">
@@ -69,7 +70,7 @@ export default function AiAlertBanner() {
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => setDismissedIds((prev) => new Set(prev).add(alert.id))}
onClick={() => setDismissedIds((prev) => new Set(prev).add(String(idx)))}
>
<X className="h-4 w-4" />
</Button>

View File

@@ -26,7 +26,7 @@ export default function AiAssistantDrawer() {
mutationFn: (message: string) =>
coachingService.chat({ message, context: { page: location.pathname } }),
onSuccess: (data) => {
setMessages((prev) => [...prev, { role: "ai", text: data.message }]);
setMessages((prev) => [...prev, { role: "ai", text: data.reply }]);
},
onError: (err: Error) => {
toast({

View File

@@ -25,6 +25,8 @@ export default function AiBatchOptimizer({ batchId }: Props) {
},
});
type OptResult = Awaited<ReturnType<typeof analyticsService.getBatchOptimization>>;
const handleOpen = () => {
if (batchId == null) {
toast({
@@ -39,9 +41,23 @@ export default function AiBatchOptimizer({ batchId }: Props) {
mutation.mutate(batchId);
};
const applyMutation = useMutation({
mutationFn: () => analyticsService.applyBatchOptimization(batchId!, mutation.data?.optimized ?? []),
onSuccess: (res) => {
toast({ title: "Suggestion Applied", description: `${res.applied} optimization(s) saved successfully.` });
setOpen(false);
},
onError: (err: Error) => {
toast({
variant: "destructive",
title: "Apply failed",
description: err.message || "Could not apply batch optimization.",
});
},
});
const handleApply = () => {
toast({ title: "Suggestion Applied", description: "Batch split recommendation has been saved successfully." });
setOpen(false);
applyMutation.mutate();
};
const onOpenChange = (next: boolean) => {
@@ -49,9 +65,10 @@ export default function AiBatchOptimizer({ batchId }: Props) {
if (!next) mutation.reset();
};
const suggestions = mutation.data ?? [];
const showResults = !mutation.isPending && !mutation.isError && suggestions.length > 0;
const showEmpty = !mutation.isPending && !mutation.isError && mutation.isSuccess && suggestions.length === 0;
const optData = mutation.data as OptResult | undefined;
const hasSuggestions = !!optData?.summary;
const showResults = !mutation.isPending && !mutation.isError && hasSuggestions;
const showEmpty = !mutation.isPending && !mutation.isError && mutation.isSuccess && !hasSuggestions;
return (
<>
@@ -71,20 +88,28 @@ export default function AiBatchOptimizer({ batchId }: Props) {
</div>
) : mutation.isError ? (
<p className="text-sm text-muted-foreground py-4 text-center">Something went wrong. Try again.</p>
) : showResults ? (
) : showResults && optData ? (
<div className="space-y-4">
<div className="space-y-3 max-h-[50vh] overflow-y-auto">
{suggestions.map((s, i) => (
<div key={i} className="rounded-lg bg-muted/30 p-4 border border-border/60">
<p className="text-xs font-semibold text-primary uppercase tracking-wide mb-1">{s.impact} impact</p>
<p className="text-sm font-medium">{s.suggestion}</p>
{s.details ? <p className="text-sm text-muted-foreground mt-2 leading-relaxed">{s.details}</p> : null}
</div>
))}
<div className="rounded-lg bg-muted/30 p-4 border border-border/60">
<p className="text-xs font-semibold text-primary uppercase tracking-wide mb-1">{optData.impact} impact</p>
<p className="text-sm font-medium">{optData.summary}</p>
</div>
{Array.isArray(optData.optimized) && optData.optimized.length > 0 && (
<div className="space-y-2 max-h-[40vh] overflow-y-auto">
{optData.optimized.map((item, i) => (
<div key={i} className="rounded-lg bg-muted/20 p-3 border text-sm">
{typeof item === "object" && item !== null ? JSON.stringify(item) : String(item)}
</div>
))}
</div>
)}
<div className="flex gap-2">
<Button className="flex-1" onClick={handleApply}>
Apply Suggestion
<Button className="flex-1" onClick={handleApply} disabled={applyMutation.isPending}>
{applyMutation.isPending ? (
<><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Applying...</>
) : (
"Apply Suggestion"
)}
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Dismiss

View File

@@ -40,8 +40,9 @@ export default function AiGeneratorModal() {
difficulty,
count,
}),
onSuccess: (res) => {
setLocalExercises(Array.isArray(res.exercises) ? res.exercises : []);
onSuccess: (res: Record<string, unknown>) => {
const items = Array.isArray(res.questions) ? res.questions : Array.isArray(res.exercises) ? res.exercises : [];
setLocalExercises(items);
},
onError: (err: Error) => {
toast({
@@ -57,6 +58,21 @@ export default function AiGeneratorModal() {
generateMutation.mutate();
};
const saveMutation = useMutation({
mutationFn: () => generationService.saveGenerated(moduleType, localExercises ?? []),
onSuccess: (res) => {
toast({ title: "Saved", description: `${res.saved} assignments saved successfully.` });
setOpen(false);
},
onError: (err: Error) => {
toast({
variant: "destructive",
title: "Save failed",
description: err.message || "Could not save generated assignments.",
});
},
});
const generated = localExercises;
const handleRemove = (index: number) => {
@@ -188,7 +204,17 @@ export default function AiGeneratorModal() {
);
})}
<div className="flex gap-2">
<Button className="flex-1">Save All</Button>
<Button
className="flex-1"
onClick={() => saveMutation.mutate()}
disabled={saveMutation.isPending || !generated?.length}
>
{saveMutation.isPending ? (
<><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving...</>
) : (
"Save All"
)}
</Button>
<Button
variant="outline"
onClick={() => {

View File

@@ -19,8 +19,8 @@ export default function AiGradeExplainer({
const explainMutation = useMutation({
mutationFn: () =>
coachingService.explain({
context: `IELTS / course grades for student: ${studentName}. Summarize what the scores mean and what to focus on next.`,
scores,
score_data: scores ?? {},
student_context: `IELTS / course grades for student: ${studentName}. Summarize what the scores mean and what to focus on next.`,
}),
onError: (err: Error) => {
toast({

View File

@@ -26,9 +26,8 @@ export default function AiGradingAssistant({
const gradeMutation = useMutation({
mutationFn: () =>
analyticsService.getGradingSuggestion({
submission_id: submissionId,
text: submissionText,
...(rubricId !== undefined ? { rubric_id: rubricId } : {}),
submission_text: submissionText,
skill: "writing",
}),
onError: (err: Error) => {
toast({
@@ -45,7 +44,7 @@ export default function AiGradingAssistant({
}, [submissionId, submissionText, rubricId]);
const data = gradeMutation.data;
const marks = data ? Math.round(data.overall_score) : 0;
const marks = data ? Math.round(data.overall_band * 100 / 9) : 0;
const feedbackBlock = data
? [
data.feedback,

View File

@@ -1,32 +1,31 @@
import { useEffect, useMemo } from "react";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Sparkles, TrendingUp, AlertTriangle, Trophy, Loader2 } from "lucide-react";
import { analyticsService } from "@/services/analytics.service";
import type { AiInsight } from "@/types";
import { Sparkles, TrendingUp, AlertTriangle, Info, Loader2 } from "lucide-react";
import { analyticsService, type AiInsightItem } from "@/services/analytics.service";
import { useToast } from "@/hooks/use-toast";
const EMPTY_PAYLOAD: Record<string, unknown> = {};
function insightIcon(type: AiInsight["type"]) {
switch (type) {
case "positive":
return Trophy;
case "warning":
function insightIcon(severity: AiInsightItem["severity"]) {
switch (severity) {
case "critical":
return AlertTriangle;
default:
case "warning":
return TrendingUp;
default:
return Info;
}
}
function insightColor(type: AiInsight["type"]) {
switch (type) {
case "positive":
return "text-primary";
function insightColor(severity: AiInsightItem["severity"]) {
switch (severity) {
case "critical":
return "text-destructive";
case "warning":
return "text-warning";
default:
return "text-success";
return "text-primary";
}
}
@@ -51,10 +50,10 @@ export default function AiInsightsPanel({ data = EMPTY_PAYLOAD }: Props) {
useEffect(() => {
mutation.mutate(data);
// eslint-disable-next-line react-hooks/exhaustive-deps -- refetch when serialized payload changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [payloadKey]);
const items = mutation.data ?? [];
const items = mutation.data?.insights ?? [];
return (
<Card className="border-0 shadow-sm">
@@ -79,19 +78,19 @@ export default function AiInsightsPanel({ data = EMPTY_PAYLOAD }: Props) {
)}
{!mutation.isPending && items.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{items.map((item) => {
const Icon = insightIcon(item.type);
const color = insightColor(item.type);
{items.map((item, idx) => {
const Icon = insightIcon(item.severity);
const color = insightColor(item.severity);
return (
<div key={item.id} className="rounded-lg border bg-muted/30 p-4">
<div key={idx} className="rounded-lg border bg-muted/30 p-4">
<div className="flex items-center gap-2 mb-2">
<Icon className={`h-4 w-4 ${color}`} />
<span className="text-sm font-semibold">{item.title}</span>
</div>
<p className="text-sm text-muted-foreground">{item.description}</p>
{item.metric != null && item.value != null && (
<p className="text-xs text-muted-foreground mt-2">
{item.metric}: {item.value}
{item.recommendation && (
<p className="text-xs text-muted-foreground mt-2 italic">
{item.recommendation}
</p>
)}
</div>

View File

@@ -27,7 +27,7 @@ export default function AiSearchBar() {
searchMutation.mutate(query.trim());
};
const results = searchMutation.data;
const result = searchMutation.data;
return (
<div className="relative max-w-md w-full">
@@ -57,35 +57,43 @@ export default function AiSearchBar() {
)}
</div>
{(searchMutation.isPending || results !== undefined) && (
{(searchMutation.isPending || result !== undefined) && (
<div className="absolute top-full mt-1 left-0 right-0 z-50 rounded-lg border bg-popover p-3 shadow-md">
{searchMutation.isPending ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
AI is searching...
</div>
) : results && results.length > 0 ? (
) : result?.answer ? (
<div className="text-sm space-y-2 max-h-64 overflow-y-auto">
{results.map((r, i) => (
<div
key={`${r.title}-${i}`}
className="flex items-start gap-2 border-b border-border/60 pb-2 last:border-0 last:pb-0"
>
<Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
<div className="min-w-0">
<p className="font-medium">{r.title}</p>
<p className="text-muted-foreground text-xs mt-0.5">{r.description}</p>
{r.url && (
<button
type="button"
className="text-xs text-primary mt-1 hover:underline"
onClick={() => navigate(r.url!)}
>
Go to {r.url}
</button>
)}
</div>
<div className="flex items-start gap-2 pb-2">
<Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
<p className="text-muted-foreground">{result.answer}</p>
</div>
{result.suggestions?.length > 0 && (
<div className="border-t pt-2 space-y-1">
<p className="text-xs font-semibold text-primary">Related queries</p>
{result.suggestions.map((s, i) => (
<button
key={i}
type="button"
className="block text-xs text-primary hover:underline"
onClick={() => { setQuery(s); searchMutation.mutate(s); }}
>
{s}
</button>
))}
</div>
)}
{result.related_actions?.map((a, i) => (
<button
key={i}
type="button"
className="text-xs text-primary hover:underline"
onClick={() => navigate(a.action)}
>
{a.label}
</button>
))}
</div>
) : (

View File

@@ -29,8 +29,11 @@ export default function AiStudyCoach() {
suggestMutation.mutate();
};
const suggestions = suggestMutation.data?.suggestions ?? [];
const planTips = suggestMutation.data?.study_plan_tips ?? [];
const d = suggestMutation.data;
const suggestions = d ? [d.suggestion, ...(d.focus_areas ?? []).map((a: string) => `Focus area: ${a}`)].filter(Boolean) : [];
const planTips = d?.daily_plan?.length
? d.daily_plan.map((p: { activity: string; duration_min: number; skill: string }) => `${p.activity} (${p.duration_min}min — ${p.skill})`)
: d?.motivation ? [d.motivation] : [];
return (
<Card className="border-0 shadow-sm bg-primary/5">

View File

@@ -50,7 +50,7 @@ export default function AiTipBanner({ context = "dashboard", variant = "tip", di
);
}
if (!data.content?.trim() && !data.title?.trim()) {
if (!data.tip?.trim()) {
return (
<div className={`rounded-lg border ${bgClass} p-3 flex items-start gap-3`}>
<Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
@@ -62,14 +62,16 @@ export default function AiTipBanner({ context = "dashboard", variant = "tip", di
);
}
const label = data.category && data.category !== "general"
? `AI ${data.category.charAt(0).toUpperCase() + data.category.slice(1)} Tip`
: `AI ${variant === "tip" ? "Tip" : variant === "insight" ? "Insight" : "Recommendation"}`;
return (
<div className={`rounded-lg border ${bgClass} p-3 flex items-start gap-3 animate-in fade-in slide-in-from-top-2 duration-300`}>
<Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
<div className="flex-1">
<span className="text-xs font-semibold text-primary">
{data.title?.trim() || `AI ${variant === "tip" ? "Tip" : variant === "insight" ? "Insight" : "Recommendation"}`}
</span>
<p className="text-sm text-muted-foreground mt-0.5">{data.content}</p>
<span className="text-xs font-semibold text-primary">{label}</span>
<p className="text-sm text-muted-foreground mt-0.5">{data.tip}</p>
</div>
{dismissible && (
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => setDismissed(true)}>

View File

@@ -22,8 +22,9 @@ export default function AiWritingHelper({ text, task_type = "ielts_writing" }: P
const mutation = useMutation({
mutationFn: (mode: NonNullable<Mode>) =>
coachingService.writingHelp({
text: text.trim(),
task_type: `${task_type}:${mode}`,
task: task_type,
draft: text.trim(),
help_type: mode,
}),
onSuccess: () => setShowResult(true),
onError: (err: Error) => {
@@ -84,20 +85,20 @@ export default function AiWritingHelper({ text, task_type = "ielts_writing" }: P
{showResult && !loading && mutation.data && activeMode === "improve" && (
<div className="space-y-3">
{mutation.data.feedback && (
{mutation.data.tips?.length > 0 && (
<div className="rounded-lg border bg-muted/30 p-3">
<p className="text-xs font-semibold text-primary mb-1 flex items-center gap-1">
<Sparkles className="h-3 w-3" /> Feedback
</p>
<p className="text-sm text-muted-foreground">{mutation.data.feedback}</p>
<p className="text-sm text-muted-foreground">{mutation.data.tips.join(" ")}</p>
</div>
)}
{mutation.data.improved && (
{mutation.data.improved_text && (
<div className="rounded-lg border bg-muted/30 p-3">
<p className="text-xs font-semibold text-primary mb-1 flex items-center gap-1">
<Sparkles className="h-3 w-3" /> Improved Version
</p>
<p className="text-sm">{mutation.data.improved}</p>
<p className="text-sm">{mutation.data.improved_text}</p>
</div>
)}
</div>
@@ -108,17 +109,17 @@ export default function AiWritingHelper({ text, task_type = "ielts_writing" }: P
<p className="text-xs font-semibold text-primary mb-1 flex items-center gap-1">
<Sparkles className="h-3 w-3" /> Grammar notes
</p>
{(mutation.data.grammar_notes?.length ?? 0) > 0 ? (
mutation.data.grammar_notes!.map((note, i) => (
{(mutation.data.changes?.length ?? 0) > 0 ? (
mutation.data.changes.map((c, i) => (
<div key={i} className="text-sm border-l-2 border-warning pl-2">
<p className="text-muted-foreground">{note}</p>
<p className="text-muted-foreground"><strong>{c.original}</strong> {c.revised} {c.reason}</p>
</div>
))
) : (
<p className="text-sm text-muted-foreground">No grammar issues flagged.</p>
)}
{mutation.data.feedback ? (
<p className="text-xs text-muted-foreground pt-2 border-t">{mutation.data.feedback}</p>
{mutation.data.tips?.length > 0 ? (
<p className="text-xs text-muted-foreground pt-2 border-t">{mutation.data.tips.join("; ")}</p>
) : null}
</div>
)}
@@ -128,9 +129,9 @@ export default function AiWritingHelper({ text, task_type = "ielts_writing" }: P
<p className="text-xs font-semibold text-primary mb-1 flex items-center gap-1">
<Sparkles className="h-3 w-3" /> Estimated band / assessment
</p>
<p className="text-sm text-muted-foreground">{mutation.data.feedback}</p>
{mutation.data.improved ? (
<p className="text-sm mt-2 pt-2 border-t">{mutation.data.improved}</p>
<p className="text-sm text-muted-foreground">{mutation.data.tips?.join(" ") ?? ""}</p>
{mutation.data.improved_text ? (
<p className="text-sm mt-2 pt-2 border-t">{mutation.data.improved_text}</p>
) : null}
</div>
)}