1 Commits

Author SHA1 Message Date
Yamen Ahmad
ca4f12a1a9 ci: add auto-deploy workflow to staging (Gitea self-hosted, syncs to monorepo)
Made-with: Cursor
2026-04-25 11:53:07 +04:00
26 changed files with 131 additions and 4891 deletions

View File

@@ -133,8 +133,6 @@ const StudentDiscussionBoard = lazy(() => import("@/pages/student/StudentDiscuss
const StudentAnnouncements = lazy(() => import("@/pages/student/StudentAnnouncements"));
const StudentMessages = lazy(() => import("@/pages/student/StudentMessages"));
const StudentJourney = lazy(() => import("@/pages/student/StudentJourney"));
const StudentCoursePlans = lazy(() => import("@/pages/student/StudentCoursePlans"));
const StudentCoursePlanDetail = lazy(() => import("@/pages/student/StudentCoursePlanDetail"));
const AiEnglishCourse = lazy(() => import("@/pages/student/AiEnglishCourse"));
const AiIeltsCourse = lazy(() => import("@/pages/student/AiIeltsCourse"));
const ExamSession = lazy(() => import("@/pages/student/ExamSession"));
@@ -271,8 +269,6 @@ const App = () => (
<Route path="/student/placement/access" element={<PlacementAccess />} />
<Route path="/student/exam/:examId/results" element={<ExamResults />} />
<Route path="/student/course/generate" element={<GapAnalysis />} />
<Route path="/student/course-plans" element={<StudentCoursePlans />} />
<Route path="/student/course-plans/:planId" element={<StudentCoursePlanDetail />} />
<Route path="/student/course/ai-english/:courseId" element={<AiEnglishCourse />} />
<Route path="/student/course/ai-ielts/:courseId" element={<AiIeltsCourse />} />
<Route path="/student/course/:courseId" element={<CourseDelivery />} />

View File

@@ -1,4 +1,4 @@
import { Outlet, Link, useNavigate, useLocation, useMatch } from "react-router-dom";
import { Outlet, Link, useNavigate, useLocation } from "react-router-dom";
import { Suspense } from "react";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import {
@@ -16,7 +16,6 @@ import AiAssistantDrawer from "@/components/ai/AiAssistantDrawer";
import AiSearchBar from "@/components/ai/AiSearchBar";
import { usePermissions } from "@/hooks/usePermissions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
DropdownMenuSeparator, DropdownMenuTrigger,
@@ -239,16 +238,9 @@ function RouteContentFallback() {
// ============= Main Layout =============
export default function AdminLmsLayout() {
const { user, logout, selectedEntity, setSelectedEntityId } = useAuth();
const { user, logout } = useAuth();
const navigate = useNavigate();
const { t } = useTranslation();
// Hide the floating "Need help?" pill on multi-step wizard routes.
// It sits at `fixed bottom-6 end-6` z-50 and was intercepting clicks
// on the wizard's own Next/Finish footer (real bug repro: trying to
// click "Next" in the Course-plan wizard at the standard 1024×768
// viewport hits the pill instead). The AI Assistant orb also at the
// bottom-right is preserved — it's smaller and useful in-wizard.
const isWizardRoute = !!useMatch("/admin/smart-wizard/*");
const initials = user?.name?.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase() ?? "??";
@@ -269,44 +261,6 @@ export default function AdminLmsLayout() {
</div>
<AiSearchBar />
<div className="flex items-center gap-2">
{user?.entities?.length ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="gap-1">
<Building2 className="h-4 w-4" />
<span className="max-w-40 truncate">
{selectedEntity?.name ?? user.entities[0]?.name ?? t("nav.entities")}
</span>
<ChevronDown className="h-3.5 w-3.5 opacity-70" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<div className="px-2 py-1.5 text-xs text-muted-foreground">
{t("nav.entities")}
</div>
<DropdownMenuSeparator />
{user.entities.map((entity) => (
<DropdownMenuItem
key={entity.id}
onClick={() => {
setSelectedEntityId(entity.id);
// Force page data to refresh against the newly
// selected entity scope.
window.location.reload();
}}
className="flex items-center justify-between gap-2"
>
<span className="truncate">{entity.name}</span>
{selectedEntity?.id === entity.id && (
<Badge variant="secondary" className="text-[10px]">
{t("common.active", "Active")}
</Badge>
)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : null}
<LanguageToggle />
<ThemeToggle />
<NotificationDropdown />
@@ -349,15 +303,13 @@ export default function AdminLmsLayout() {
</div>
</div>
<AiAssistantDrawer />
{!isWizardRoute && (
<Link
to="/admin/tickets"
className="fixed bottom-6 end-6 z-40 flex items-center gap-2 rounded-full bg-primary px-4 py-2.5 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
>
<HelpCircle className="h-4 w-4" />
<span className="text-sm font-medium">{t("chrome.needHelp")}</span>
</Link>
)}
<Link
to="/admin/tickets"
className="fixed bottom-6 end-6 z-50 flex items-center gap-2 rounded-full bg-primary px-4 py-2.5 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
>
<HelpCircle className="h-4 w-4" />
<span className="text-sm font-medium">{t("chrome.needHelp")}</span>
</Link>
</SidebarProvider>
);
}

View File

@@ -1,4 +1,4 @@
import { Outlet, useLocation, Link, useNavigate, useMatch } from "react-router-dom";
import { Outlet, useLocation, Link, useNavigate } from "react-router-dom";
import { Suspense } from "react";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/AppSidebar";
@@ -7,16 +7,14 @@ import {
BreadcrumbPage, BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Ticket, Settings, User, LogOut, HelpCircle, Building2, ChevronDown } from "lucide-react";
import { Ticket, Settings, User, LogOut, HelpCircle } from "lucide-react";
import React from "react";
import AiAssistantDrawer from "@/components/ai/AiAssistantDrawer";
import AiSearchBar from "@/components/ai/AiSearchBar";
import { useAuth } from "@/contexts/AuthContext";
const routeLabels: Record<string, string> = {
"dashboard": "Dashboard",
@@ -92,14 +90,6 @@ function RouteContentFallback() {
export default function AppLayout() {
const navigate = useNavigate();
const { user, selectedEntity, setSelectedEntityId } = useAuth();
// Hide the floating "Need help?" pill on multi-step wizard routes.
// The pill sits at `fixed bottom-6 right-6` with z-50 and was
// intercepting clicks on the wizard's own Next/Finish footer at most
// viewport heights, blocking users from finishing the flow. The AI
// Assistant orb (also bottom-right) stays — it's smaller and
// genuinely useful inside the wizard.
const isWizardRoute = !!useMatch("/admin/smart-wizard/*");
return (
<SidebarProvider>
@@ -113,34 +103,6 @@ export default function AppLayout() {
</div>
<AiSearchBar />
<div className="flex items-center gap-2">
{user?.entities?.length ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="gap-1">
<Building2 className="h-4 w-4" />
<span className="max-w-40 truncate">
{selectedEntity?.name ?? user.entities[0]?.name ?? "Entity"}
</span>
<ChevronDown className="h-3.5 w-3.5 opacity-70" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
{user.entities.map((entity) => {
const active = selectedEntity?.id === entity.id;
return (
<DropdownMenuItem
key={entity.id}
onClick={() => setSelectedEntityId(entity.id)}
className="flex items-center justify-between gap-3"
>
<span className="truncate">{entity.name}</span>
{active ? <Badge variant="secondary">Current</Badge> : null}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
) : null}
<Button variant="ghost" size="icon" onClick={() => navigate("/tickets")} className="text-muted-foreground hover:text-foreground">
<Ticket className="h-4 w-4" />
</Button>
@@ -183,15 +145,14 @@ export default function AppLayout() {
</div>
</div>
<AiAssistantDrawer />
{!isWizardRoute && (
<Link
to="/tickets"
className="fixed bottom-6 right-6 z-40 flex items-center gap-2 rounded-full bg-primary px-4 py-2.5 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
>
<HelpCircle className="h-4 w-4" />
<span className="text-sm font-medium">Need help?</span>
</Link>
)}
{/* Floating help button */}
<Link
to="/tickets"
className="fixed bottom-6 right-6 z-50 flex items-center gap-2 rounded-full bg-primary px-4 py-2.5 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
>
<HelpCircle className="h-4 w-4" />
<span className="text-sm font-medium">Need help?</span>
</Link>
</SidebarProvider>
);
}

View File

@@ -3,7 +3,7 @@ import ExamPopup from "./student/ExamPopup";
import {
LayoutDashboard, BookOpen, ClipboardList, BarChart3,
CalendarCheck, Calendar, User, Target, ListChecks,
MessageSquare, Megaphone, Mail, TrendingUp, Sparkles,
MessageSquare, Megaphone, Mail, TrendingUp,
} from "lucide-react";
/**
@@ -17,7 +17,6 @@ const navGroups: NavGroup[] = [
items: [
{ titleKey: "nav.dashboard", url: "/student/dashboard", icon: LayoutDashboard },
{ titleKey: "nav.myCourses", url: "/student/courses", icon: BookOpen },
{ titleKey: "nav.myCoursePlans", url: "/student/course-plans", icon: Sparkles },
{ titleKey: "nav.subjectRegistration", url: "/student/subject-registration", icon: ListChecks },
{ titleKey: "nav.assignments", url: "/student/assignments", icon: ClipboardList },
],

View File

@@ -1,214 +0,0 @@
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { Library, Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Skeleton } from "@/components/ui/skeleton";
import { resourcesService } from "@/services/resources.service";
import type { Resource } from "@/types";
/**
* Generic, reusable picker over `/api/resources`.
*
* Two callers wire this up today:
*
* 1. **AdminCoursePlanDetail** — for an *existing* plan, so it forwards
* the picked resources to `coursePlanService.attachResources` in the
* `onConfirm` handler and invalidates the sources query.
*
* 2. **CoursePlanWizard** — the plan does not exist yet at pick time,
* so the wizard simply pushes the picks into its draft state and
* attaches them in one batch after the plan is created.
*
* The dialog itself is purposefully agnostic: it only reports the
* selected `Resource` rows; the parent decides what to do.
*/
export function LibraryPickerDialog({
open,
onOpenChange,
alreadyLinkedIds,
onConfirm,
isPending,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
/** Resources whose ids are in this set render disabled + checked. */
alreadyLinkedIds?: Set<number>;
/** Called when the admin clicks "Attach selected". */
onConfirm: (resources: Resource[]) => void | Promise<void>;
/** Optional spinner state from the parent's mutation. */
isPending?: boolean;
}) {
const { t } = useTranslation();
const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState<string>("all");
const [selected, setSelected] = useState<Set<number>>(new Set());
// Reset every time the dialog re-opens so a previous session's
// selection doesn't bleed into the next attach.
useEffect(() => {
if (open) {
setSelected(new Set());
setSearch("");
setTypeFilter("all");
}
}, [open]);
const { data, isLoading } = useQuery({
queryKey: ["library-resources", { search, type: typeFilter }],
queryFn: () =>
resourcesService.list({
search: search || undefined,
resource_type: typeFilter === "all" ? undefined : typeFilter,
review_status: "approved",
}),
enabled: open,
});
const resources: Resource[] = data?.items ?? [];
const toggle = (id: number) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const handleConfirm = async () => {
const picked = resources.filter((r) => selected.has(r.id));
if (!picked.length) return;
await onConfirm(picked);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[640px] max-h-[85vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Library className="h-5 w-5 text-primary" />
{t("coursePlan.sources.libraryTitle")}
</DialogTitle>
<DialogDescription>
{t("coursePlan.sources.libraryDescription")}
</DialogDescription>
</DialogHeader>
<div className="flex gap-2 pt-2">
<Input
placeholder={t("coursePlan.sources.librarySearchPlaceholder")}
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1"
/>
<Select value={typeFilter} onValueChange={setTypeFilter}>
<SelectTrigger className="w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">
{t("coursePlan.sources.libraryTypeAll")}
</SelectItem>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="document">DOCX</SelectItem>
<SelectItem value="link">URL</SelectItem>
<SelectItem value="article">Article</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex-1 overflow-y-auto -mx-2 px-2 space-y-1">
{isLoading && <Skeleton className="h-32 w-full" />}
{!isLoading && resources.length === 0 && (
<p className="text-center text-sm text-muted-foreground py-8">
{t("coursePlan.sources.libraryEmpty")}
</p>
)}
{!isLoading &&
resources.map((r) => {
const isLinked = alreadyLinkedIds?.has(r.id) ?? false;
const isSelected = selected.has(r.id);
return (
<label
key={r.id}
className={`flex items-start gap-3 rounded-md border p-2 text-sm transition-colors ${
isLinked
? "opacity-60 cursor-not-allowed bg-muted/40"
: "cursor-pointer hover:bg-accent/50"
}`}
>
<Checkbox
checked={isLinked || isSelected}
disabled={isLinked}
onCheckedChange={() => !isLinked && toggle(r.id)}
className="mt-0.5"
/>
<div className="flex-1 min-w-0 space-y-0.5">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium truncate">{r.name}</span>
<Badge
variant="outline"
className="text-[10px] capitalize"
>
{r.resource_type || r.type || "resource"}
</Badge>
{isLinked && (
<Badge variant="secondary" className="text-[10px]">
{t("coursePlan.sources.libraryAlreadyLinked")}
</Badge>
)}
</div>
{(r.subject_name || (r.topic_names ?? []).length > 0) && (
<p className="text-xs text-muted-foreground truncate">
{[r.subject_name, ...(r.topic_names?.slice(0, 2) ?? [])]
.filter(Boolean)
.join(" ")}
</p>
)}
</div>
</label>
);
})}
</div>
<DialogFooter className="border-t pt-3">
<span className="mr-auto text-xs text-muted-foreground self-center">
{t("coursePlan.sources.librarySelectedCount", {
count: selected.size,
})}
</span>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t("common.cancel", "Cancel")}
</Button>
<Button
onClick={handleConfirm}
disabled={!selected.size || isPending}
>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t("coursePlan.sources.libraryAttach")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,78 +0,0 @@
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import type { CoursePlanMaterial } from "@/types";
export const SKILL_STYLE: Record<string, string> = {
reading: "bg-blue-100 text-blue-800 border-blue-200",
writing: "bg-purple-100 text-purple-800 border-purple-200",
listening: "bg-emerald-100 text-emerald-800 border-emerald-200",
speaking: "bg-amber-100 text-amber-800 border-amber-200",
grammar: "bg-rose-100 text-rose-800 border-rose-200",
vocabulary: "bg-cyan-100 text-cyan-800 border-cyan-200",
integrated: "bg-slate-100 text-slate-800 border-slate-200",
};
export function SkillBadge({ skill }: { skill: string }) {
return (
<Badge
variant="outline"
className={cn("capitalize border", SKILL_STYLE[skill] ?? SKILL_STYLE.integrated)}
>
{skill || "integrated"}
</Badge>
);
}
function renderAny(value: unknown): React.ReactNode {
if (value == null) return null;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return <p className="leading-7">{String(value)}</p>;
}
if (Array.isArray(value)) {
if (value.length === 0) return null;
return (
<ul className="list-disc ps-5 space-y-1">
{value.map((item, idx) => (
<li key={idx}>{renderAny(item)}</li>
))}
</ul>
);
}
if (typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>);
return (
<div className="space-y-3">
{entries.map(([k, v]) => (
<div key={k}>
<h5 className="font-medium capitalize text-sm text-muted-foreground mb-1">
{k.replace(/_/g, " ")}
</h5>
<div className="text-sm">{renderAny(v)}</div>
</div>
))}
</div>
);
}
return null;
}
export default function MaterialBookView({
material,
}: {
material: Pick<CoursePlanMaterial, "body" | "body_text" | "material_type">;
}) {
const body = material.body ?? {};
const hasStructured = Object.keys(body).length > 0;
return (
<div className="rounded-lg border bg-background/70 p-4 space-y-4">
{hasStructured ? (
renderAny(body)
) : (
<p className="text-sm whitespace-pre-wrap leading-7">
{material.body_text || "No content available yet."}
</p>
)}
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
import { authService } from "@/services/auth.service";
import { clearToken, getActiveEntityId, setActiveEntityId } from "@/lib/api-client";
import { clearToken } from "@/lib/api-client";
import type { User, UserRole } from "@/types/auth";
export type { UserRole };
@@ -9,9 +9,6 @@ interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
selectedEntityId: number | null;
selectedEntity: User["entities"][number] | null;
setSelectedEntityId: (entityId: number | null) => void;
login: (email: string, password: string) => Promise<User>;
logout: () => Promise<void>;
}
@@ -20,23 +17,8 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [selectedEntityId, setSelectedEntityIdState] = useState<number | null>(getActiveEntityId());
const [isLoading, setIsLoading] = useState(true);
const syncEntitySelection = useCallback((nextUser: User | null) => {
const available = nextUser?.entities ?? [];
if (available.length === 0) {
setSelectedEntityIdState(null);
setActiveEntityId(null);
return;
}
const stored = getActiveEntityId();
const validStored = stored && available.some((e) => e.id === stored) ? stored : null;
const next = validStored ?? available[0].id;
setSelectedEntityIdState(next);
setActiveEntityId(next);
}, []);
useEffect(() => {
const token = localStorage.getItem("encoach_token");
if (!token) {
@@ -46,61 +28,30 @@ export function AuthProvider({ children }: { children: ReactNode }) {
authService
.getUser()
.then((u) => {
setUser(u);
syncEntitySelection(u);
})
.then(setUser)
.catch(() => {
clearToken();
setActiveEntityId(null);
})
.finally(() => setIsLoading(false));
}, [syncEntitySelection]);
}, []);
const login = useCallback(async (email: string, password: string): Promise<User> => {
const res = await authService.login({ login: email, password });
setUser(res.user);
syncEntitySelection(res.user);
return res.user;
}, [syncEntitySelection]);
const setSelectedEntityId = useCallback((entityId: number | null) => {
if (!user) {
setSelectedEntityIdState(null);
setActiveEntityId(null);
return;
}
if (entityId == null) {
setSelectedEntityIdState(null);
setActiveEntityId(null);
return;
}
if (!user.entities.some((e) => e.id === entityId)) return;
setSelectedEntityIdState(entityId);
setActiveEntityId(entityId);
}, [user]);
}, []);
const logout = useCallback(async () => {
await authService.logout();
setUser(null);
setSelectedEntityIdState(null);
setActiveEntityId(null);
}, []);
const selectedEntity =
user?.entities.find((e) => e.id === selectedEntityId) ??
user?.entities[0] ??
null;
return (
<AuthContext.Provider
value={{
user,
isAuthenticated: !!user,
isLoading,
selectedEntityId,
selectedEntity,
setSelectedEntityId,
login,
logout,
}}

View File

@@ -60,7 +60,6 @@ const ar: Translations = {
dashboard: "لوحة التحكم",
courses: "الدورات",
myCourses: "دوراتي",
myCoursePlans: "خططي الدراسية",
students: "الطلاب",
teachers: "المعلمون",
batches: "الدفعات",
@@ -740,14 +739,8 @@ const ar: Translations = {
basicsDesc: "سمِّ المقرر وحدّد المستوى والمدة وعدد الساعات الأسبوعية.",
coverage: "التغطية",
coverageDesc: "أخبر الذكاء الاصطناعي بتوزيع الساعات على المهارات ومن هم المتعلّمون.",
sources: "المصادر المرجعية",
sourcesDesc:
"ارفع ملفات PDF أو روابط أو نصوص. يستخدمها الذكاء الاصطناعي كمرجع لتوليد مواد كل أسبوع.",
scope: "النطاق",
scopeDesc: "اختياري: تركيز القواعد، والمصادر، وملاحظات حرّة.",
media: "الوسائط",
mediaDesc:
"اختر أي وسائط يولّدها الذكاء الاصطناعي تلقائياً مع المواد النصّية.",
review: "المراجعة",
reviewDesc: "راجع البيانات قبل بدء التوليد.",
},
@@ -774,178 +767,7 @@ const ar: Translations = {
cefrRequired: "يرجى اختيار مستوى CEFR.",
weeksRange: "عدد الأسابيع يجب أن يكون 1 على الأقل.",
},
review: {
sourcesCount_one: "{{count}} مصدر",
sourcesCount_other: "{{count}} مصادر",
noSources: "لا توجد مصادر",
mediaNone: "لا يوجد توليد وسائط",
},
},
sections_extras: {
sources: "المصادر المرجعية",
progress: "تقدّم التوليد",
assignments: "الإسنادات",
media: "الوسائط المُولَّدة",
},
sources: {
sectionTitle: "المصادر المرجعية (RAG)",
sectionDesc:
"ارفع PDF أو أضف روابط أو نصوصاً. يستخدمها الذكاء الاصطناعي كمرجع عند توليد المواد الأسبوعية.",
collected_one: "{{count}} مصدر جاهز",
collected_other: "{{count}} مصادر جاهزة",
empty: "لا توجد مصادر مرجعية بعد.",
dropTitle: "أضف مواد مرجعية",
dropHint: "PDF أو DOCX أو TXT أو HTML أو نص — حتى بضعة ميغابايت لكل ملف.",
uploadFiles: "رفع ملفات",
urlLabel: "إضافة رابط",
textLabel: "أو ألصق نصاً مباشرة",
textPlaceholder: "ألصق فقرة لتوجيه الذكاء الاصطناعي…",
uploadFailed: "تعذّر رفع \"{{name}}\".",
reindex: "إعادة فهرسة",
reindexed: "أُعيدت فهرسة المصدر.",
reindexFailed: "فشلت إعادة الفهرسة.",
deleted: "تم حذف المصدر.",
deleteFailed: "تعذّر حذف المصدر.",
status: {
pending: "في الانتظار",
indexing: "يُفهرس…",
indexed: "مُفهرس",
failed: "فشل",
},
kindLabel: {
file: "ملف",
url: "رابط",
text: "نص",
resource: "المكتبة",
},
chunks_one: "{{count}} جزء",
chunks_other: "{{count}} أجزاء",
pickFromLibrary: "اختيار من المكتبة",
libraryHint: "أعد استخدام مورد قمت برفعه من قبل.",
libraryTitle: "اختر من مكتبة الموارد",
libraryDescription:
"اختر مورداً واحداً أو أكثر من الموارد المعتمدة لدعم الذكاء الاصطناعي. سنقوم بفهرستها تماماً مثل الملفات المرفوعة.",
librarySearchPlaceholder: "ابحث بالعنوان…",
libraryTypeAll: "كل الأنواع",
libraryEmpty: "لا توجد موارد مطابقة لهذه الفلاتر.",
libraryAlreadyLinked: "مربوط مسبقاً",
libraryAttach: "ربط المختار",
librarySelectedCount_one: "تم اختيار {{count}}",
librarySelectedCount_other: "تم اختيار {{count}}",
libraryAttached_one: "تم ربط {{count}} مورد.",
libraryAttached_other: "تم ربط {{count}} موارد.",
librarySkipped_one: "{{count}} مورد كان مربوطاً مسبقاً.",
librarySkipped_other: "{{count}} موارد كانت مربوطة مسبقاً.",
libraryAttachFailed: "تعذّر ربط الموارد المختارة.",
linkedToLibrary: "مرتبط بـ /admin/resources",
fromLibrary: "المكتبة",
libraryPickTitle: "اختر من المكتبة",
libraryPickHint: "أعد استخدام موارد معتمدة سبق رفعها إلى /admin/resources.",
libraryPickButton: "تصفح المكتبة",
},
sourceKind: {
file: "ملف",
url: "رابط",
text: "نص",
},
deliverables: {
title: "تقدّم التوليد",
subtitle:
"ما الذي سيُنتجه الذكاء الاصطناعي، وما تم إنتاجه، وما اكتمل تماماً (مواد + وسائط).",
summary: {
planned_one: "{{count}} مخطّط",
planned_other: "{{count}} مخطّط",
generated_one: "{{count}} مُولَّد",
generated_other: "{{count}} مُولَّد",
ready_one: "{{count}} جاهز",
ready_other: "{{count}} جاهز",
},
mediaCounts: "صوت {{audio}} · صورة {{image}} · فيديو {{video}}",
status: {
planned: "مخطّط",
generated: "مُولَّد",
ready: "جاهز",
},
perWeek: "تفصيل لكل أسبوع",
noWeeks: "لا توجد أسابيع — ولّد الخطة أولاً.",
},
media: {
audio: "صوت",
image: "صورة",
video: "فيديو",
audioTitle: "تعليق صوتي",
audioDesc:
"توليد صوت منطوق (Polly / ElevenLabs) لنصوص الاستماع ومحفّزات المحادثة.",
imageTitle: "صور تغطية",
imageDesc:
"توليد صور DALL·E 3 لنصوص القراءة والاستماع. يحتسب من ميزانية الصور للخطة.",
videoTitle: "فيديو شرائح",
videoDesc: "دمج الصوت + الصورة في فيديو MP4 قصير عبر ffmpeg. أبطأ الخيارات.",
hint:
"الصوت مفعّل افتراضياً. الفيديو معطّل افتراضياً — فعّله بعد مراجعة الصوت والصورة.",
drawerTitle: "وسائط \"{{title}}\"",
drawerSubtitle: "ولّد أو احذف الصوت والصورة والفيديو.",
generateAudio: "توليد صوت",
generateImage: "توليد صورة",
generateVideo: "توليد فيديو",
generating: "جاري التوليد…",
audioReady: "الصوت جاهز",
imageReady: "الصورة جاهزة",
videoReady: "الفيديو جاهز",
audioFailed: "فشل توليد الصوت.",
imageFailed: "فشل توليد الصورة.",
videoFailed: "فشل توليد الفيديو.",
deleted: "تم حذف الوسيط.",
deleteFailed: "تعذّر حذف الوسيط.",
open: "فتح",
download: "تنزيل",
noMedia: "لا توجد وسائط لهذه المادة بعد.",
mediaForMaterial: "وسائط",
bulk: "توليد وسائط الأسبوع",
bulkSuccess: "اكتمل توليد وسائط الأسبوع.",
bulkFailed: "تعذّر توليد وسائط الأسبوع.",
provider: "المزوّد",
},
assignments: {
title: "مُسندة إلى",
empty: "لم تُسند إلى أحد بعد.",
assign: "إسناد",
assignTitle: "إسناد خطة المقرر",
assignSubtitle:
"اختر شعبة (دفعة) للجميع، أو طلاباً محدّدين. ستظهر الخطة في لوحة الطالب.",
modeBatch: "دفعة كاملة",
modeStudents: "طلاب محدّدون",
pickBatch: "اختر دفعة",
pickStudents: "اختر طلاباً",
noBatches: "لا توجد دفعات.",
noStudents: "لا يوجد طلاب.",
dueDate: "تاريخ التسليم (اختياري)",
message: "رسالة للمتعلّمين (اختياري)",
messagePlaceholder: "ترحيب، توقّعات، مواعيد…",
created: "تم إسناد الخطة.",
createFailed: "تعذّر إسناد الخطة.",
removed: "تمت إزالة الإسناد.",
removeFailed: "تعذّر إزالة الإسناد.",
remove: "إزالة",
confirmRemove: "إزالة هذا الإسناد؟",
assignedBy: "أسندها {{name}}",
students_one: "{{count}} طالب",
students_other: "{{count}} طلاب",
cancel: "إلغاء",
save: "إسناد",
},
student: {
listTitle: "خططي الدراسية",
listSubtitle:
"خطط مناهج مخصّصة يُنشئها الذكاء الاصطناعي ويُسندها معلّمك. افتح خطة لرؤية الأسابيع والمواد والوسائط.",
empty: "لم تُسند إليك خطط بعد.",
open: "فتح المقرر",
assignedBy: "أسندها {{name}}",
due: "موعد التسليم {{date}}",
noDue: "بدون موعد",
backToList: "العودة إلى خططي",
},
wizardSourcesStep: "المصادر",
},
aiAdmin: {
title: "وكلاء الذكاء الاصطناعي والأدوات",
@@ -955,83 +777,6 @@ const ar: Translations = {
agents: "الوكلاء",
tools: "الأدوات",
prompts: "التعليمات",
providers: "المزوّدون والمفاتيح",
},
},
aiProviders: {
title: "مزوّدو الذكاء الاصطناعي ومفاتيح API",
subtitle:
"اختر المزوّد الفعّال لكل قدرة واحفظ مفاتيح API. تُطبَّق التغييرات في الطلب التالي مباشرةً دون الحاجة لإعادة تشغيل Odoo.",
activeProvider: "المزوّد الفعّال",
save: "حفظ الإعدادات",
testButton: "اختبار سلسلة الاحتياط",
noPaidKeys:
"لا توجد مفاتيح API مدفوعة لهذه القدرة — سيتم استخدام البديل المجاني.",
paidConfigured: "المزوّدون المدفوعون المهيَّؤون:",
empty: "تعذّر تحميل الإعدادات.",
footer:
"تُقرأ إعدادات المزوّدين من ir.config_parameter في كل طلب — بدون تخزين مؤقّت ولا حاجة لإعادة تشغيل.",
cap: {
text: "توليد النصوص",
text_hint: "يستخدمه كل وكلاء LangGraph (مخطّط المقرر، مولّد الاختبارات، المصحّحون).",
image: "توليد الصور",
image_hint: "رسومات لنصوص القراءة ومشاهد الاستماع وبطاقات المفردات.",
audio: "الصوت (TTS)",
audio_hint: "سرد نصوص الاستماع وأمثلة إجابات أسئلة المحادثة.",
video: "تركيب الفيديو",
video_hint: "مقاطع MP4 تجمع بين الصورة المُولَّدة والسرد الصوتي.",
},
kind: {
paid: "مدفوع",
free: "مجاني",
auto: "تلقائي",
},
keys: {
title: "مفاتيح API",
subtitle:
"المفاتيح للكتابة فقط وتُحفَظ مشفّرة في ir.config_parameter. لا تُرجَع أبداً إلى المتصفّح.",
saved: "محفوظ",
unsaved: "غير محفوظ",
clear: "مسح",
placeholderSaved: "•••••• (انقر للاستبدال)",
openai: "مفتاح OpenAI",
openai_hint: "يُستخدَم لـ GPT-4o والتضمين و DALL-E 3.",
aws_access: "AWS Access Key ID",
aws_secret: "AWS Secret Access Key",
elevenlabs: "مفتاح ElevenLabs",
gptzero: "مفتاح GPTZero",
paymob_api: "مفتاح Paymob API",
paymob_integration: "Paymob integration ID",
paymob_iframe: "Paymob iframe ID",
paymob_hmac: "Paymob HMAC secret",
},
group: {
openai: "OpenAI",
aws: "AWS Polly",
elevenlabs: "ElevenLabs",
other: "خدمات ذكاء اصطناعي أخرى",
paymob: "Paymob (المدفوعات)",
},
plain: {
title: "النموذج والتشغيل",
subtitle:
"معلَمات تشغيل غير سرّية: النموذج الافتراضي، منطقة AWS، مهلة الطلب.",
openai_model: "نموذج OpenAI",
openai_fast: "نموذج OpenAI السريع",
aws_region: "منطقة AWS",
elevenlabs_model: "نموذج ElevenLabs",
timeout: "مهلة الطلب (ثوانٍ)",
max_retries: "أقصى عدد محاولات",
},
toast: {
loadFailed: "تعذّر تحميل إعدادات الذكاء الاصطناعي",
saved: "تم حفظ إعدادات المزوّد",
savedDescription:
"تم تحديث المزوّدين. تُطبَّق التغييرات في الطلب التالي.",
saveFailed: "تعذّر حفظ الإعدادات",
testOk: "سلسلة المزوّد جاهزة",
testPartial: "بعض المزوّدين تنقصه بيانات الاعتماد",
testFailed: "فشل اختبار المزوّد",
},
},
agents: {

View File

@@ -44,8 +44,6 @@ export interface Translations {
aiAdmin: Record<string, unknown>;
agents: Record<string, unknown>;
tools: Record<string, unknown>;
/** AI provider selection & API key management (Providers & Keys tab). */
aiProviders: Record<string, unknown>;
}
const en: Translations = {
@@ -107,7 +105,6 @@ const en: Translations = {
dashboard: "Dashboard",
courses: "Courses",
myCourses: "My Courses",
myCoursePlans: "My Course Plans",
students: "Students",
teachers: "Teachers",
batches: "Batches",
@@ -799,14 +796,8 @@ const en: Translations = {
basicsDesc: "Name the course and set level, duration, and weekly hours.",
coverage: "Coverage",
coverageDesc: "Tell the AI how hours split across skills and who the learners are.",
sources: "Reference sources",
sourcesDesc:
"Drop PDFs, URLs, or pasted text. The AI uses them as grounding when generating each week's materials.",
scope: "Scope",
scopeDesc: "Optional: grammar focus, resources to reference, free-form notes.",
media: "Multimedia",
mediaDesc:
"Pick which media the AI should auto-produce alongside the text materials.",
review: "Review",
reviewDesc: "Double-check your brief before kicking off the generation.",
},
@@ -834,180 +825,7 @@ const en: Translations = {
cefrRequired: "Please pick a CEFR level.",
weeksRange: "Total weeks must be at least 1.",
},
review: {
sourcesCount_one: "{{count}} reference source",
sourcesCount_other: "{{count}} reference sources",
noSources: "No reference sources",
mediaNone: "No media generation",
},
},
sections_extras: {
sources: "Reference sources",
progress: "Generation progress",
assignments: "Assignments",
media: "Generated media",
},
sources: {
sectionTitle: "Reference sources (RAG)",
sectionDesc:
"Upload PDFs, paste URLs, or drop in raw text. The AI will use the indexed content as grounding when it writes weekly materials.",
collected_one: "{{count}} source ready",
collected_other: "{{count}} sources ready",
empty: "No reference sources yet.",
dropTitle: "Add reference materials",
dropHint: "PDF, DOCX, TXT, HTML, or plain text — up to a few MB each.",
uploadFiles: "Upload files",
urlLabel: "Add a URL",
textLabel: "Or paste text directly",
textPlaceholder: "Paste a passage to ground the AI on…",
uploadFailed: "Couldn't upload \"{{name}}\".",
reindex: "Reindex",
reindexed: "Source reindexed.",
reindexFailed: "Reindex failed.",
deleted: "Source deleted.",
deleteFailed: "Couldn't delete source.",
status: {
pending: "Pending",
indexing: "Indexing…",
indexed: "Indexed",
failed: "Failed",
},
kindLabel: {
file: "File",
url: "URL",
text: "Text",
resource: "Library",
},
chunks_one: "{{count}} chunk",
chunks_other: "{{count}} chunks",
// Library picker — reuses /admin/resources items as RAG sources.
pickFromLibrary: "Pick from library",
libraryHint: "Reuse a resource you've already uploaded.",
libraryTitle: "Pick from resource library",
libraryDescription:
"Select one or more approved resources to ground the AI on. We'll index them just like uploaded files.",
librarySearchPlaceholder: "Search by title…",
libraryTypeAll: "All types",
libraryEmpty: "No resources match those filters.",
libraryAlreadyLinked: "Already linked",
libraryAttach: "Attach selected",
librarySelectedCount_one: "{{count}} selected",
librarySelectedCount_other: "{{count}} selected",
libraryAttached_one: "Attached {{count}} resource.",
libraryAttached_other: "Attached {{count}} resources.",
librarySkipped_one: "{{count}} resource was already linked.",
librarySkipped_other: "{{count}} resources were already linked.",
libraryAttachFailed: "Couldn't attach the selected resources.",
linkedToLibrary: "Linked to /admin/resources",
fromLibrary: "Library",
libraryPickTitle: "Pick from library",
libraryPickHint: "Reuse approved resources you've already uploaded to /admin/resources.",
libraryPickButton: "Browse library",
},
sourceKind: {
file: "File",
url: "URL",
text: "Inline text",
},
deliverables: {
title: "Generation progress",
subtitle:
"What the AI is going to produce, what it has produced, and what is fully ready (materials + media).",
summary: {
planned_one: "{{count}} planned",
planned_other: "{{count}} planned",
generated_one: "{{count}} generated",
generated_other: "{{count}} generated",
ready_one: "{{count}} ready",
ready_other: "{{count}} ready",
},
mediaCounts: "Audio {{audio}} · Image {{image}} · Video {{video}}",
status: {
planned: "Planned",
generated: "Generated",
ready: "Ready",
},
perWeek: "Per-week breakdown",
noWeeks: "No weeks yet — generate the plan first.",
},
media: {
audio: "Audio",
image: "Image",
video: "Video",
audioTitle: "Narration audio",
audioDesc:
"Generate spoken audio (Polly / ElevenLabs) for listening scripts and speaking prompts.",
imageTitle: "Cover images",
imageDesc:
"Generate DALL·E 3 images for reading texts and listening scripts. Counts against the per-plan image budget.",
videoTitle: "Slideshow video",
videoDesc:
"Combine audio + image into a short MP4 with ffmpeg. Slowest option.",
hint:
"Audio is on by default. Video is off by default — turn it on once you've reviewed the audio + image.",
drawerTitle: "Media for \"{{title}}\"",
drawerSubtitle: "Generate or remove audio, images, and slideshow video.",
generateAudio: "Generate audio",
generateImage: "Generate image",
generateVideo: "Generate video",
generating: "Generating…",
audioReady: "Audio ready",
imageReady: "Image ready",
videoReady: "Video ready",
audioFailed: "Audio generation failed.",
imageFailed: "Image generation failed.",
videoFailed: "Video generation failed.",
deleted: "Media deleted.",
deleteFailed: "Couldn't delete media.",
open: "Open",
download: "Download",
noMedia: "No media yet for this material.",
mediaForMaterial: "Media",
bulk: "Generate week media",
bulkSuccess: "Week media generation done.",
bulkFailed: "Couldn't generate week media.",
provider: "Provider",
},
assignments: {
title: "Assigned to",
empty: "Not assigned to anyone yet.",
assign: "Assign",
assignTitle: "Assign this course plan",
assignSubtitle:
"Pick a class (batch) for everyone, or individual students. They'll see the plan in their student dashboard.",
modeBatch: "Whole class (batch)",
modeStudents: "Individual students",
pickBatch: "Select a batch",
pickStudents: "Pick students",
noBatches: "No batches available.",
noStudents: "No students available.",
dueDate: "Due date (optional)",
message: "Message to learners (optional)",
messagePlaceholder: "Welcome note, expectations, deadlines…",
created: "Plan assigned.",
createFailed: "Couldn't assign plan.",
removed: "Assignment removed.",
removeFailed: "Couldn't remove assignment.",
remove: "Remove",
confirmRemove: "Remove this assignment?",
assignedBy: "Assigned by {{name}}",
students_one: "{{count}} student",
students_other: "{{count}} students",
cancel: "Cancel",
save: "Assign",
},
student: {
listTitle: "My course plans",
listSubtitle:
"Personalised AI-generated curricula assigned by your teacher. Open one to see the weekly plan, materials, and media.",
empty: "No plans assigned to you yet.",
open: "Open course",
assignedBy: "Assigned by {{name}}",
due: "Due {{date}}",
noDue: "No deadline",
backToList: "Back to my plans",
},
wizardSourcesStep: "Sources",
},
aiAdmin: {
title: "AI Agents & Tools",
@@ -1017,83 +835,6 @@ const en: Translations = {
agents: "Agents",
tools: "Tools",
prompts: "Prompts",
providers: "Providers & Keys",
},
},
aiProviders: {
title: "AI Providers & API Keys",
subtitle:
"Pick the active provider per capability and store API keys. Changes take effect on the next request — no Odoo restart required.",
activeProvider: "Active provider",
save: "Save settings",
testButton: "Test fallback chain",
noPaidKeys:
"No paid API keys configured for this capability — free fallback will be used.",
paidConfigured: "Configured paid providers:",
empty: "Settings could not be loaded.",
footer:
"Provider settings are read fresh from ir.config_parameter on every request — no caching, no restart required.",
cap: {
text: "Text generation",
text_hint: "Used by every LangGraph agent (course planner, exam generator, graders).",
image: "Image generation",
image_hint: "Illustrations for reading texts, listening scenes, and vocabulary cards.",
audio: "Audio (TTS)",
audio_hint: "Listening-script narration and speaking-prompt model answers.",
video: "Video composition",
video_hint: "Slideshow MP4s combining a generated image with the audio narration.",
},
kind: {
paid: "Paid",
free: "Free",
auto: "Auto",
},
keys: {
title: "API keys",
subtitle:
"Keys are write-only and stored encrypted at rest in ir.config_parameter. They are never returned to the browser.",
saved: "Saved",
unsaved: "Unsaved",
clear: "Clear",
placeholderSaved: "•••••• (click to replace)",
openai: "OpenAI API key",
openai_hint: "Used for GPT-4o, embeddings, and DALL-E 3.",
aws_access: "AWS Access Key ID",
aws_secret: "AWS Secret Access Key",
elevenlabs: "ElevenLabs API key",
gptzero: "GPTZero API key",
paymob_api: "Paymob API key",
paymob_integration: "Paymob integration ID",
paymob_iframe: "Paymob iframe ID",
paymob_hmac: "Paymob HMAC secret",
},
group: {
openai: "OpenAI",
aws: "AWS Polly",
elevenlabs: "ElevenLabs",
other: "Other AI services",
paymob: "Paymob (payments)",
},
plain: {
title: "Model & runtime",
subtitle:
"Non-secret runtime parameters: default model, AWS region, request timeout.",
openai_model: "OpenAI model",
openai_fast: "OpenAI fast model",
aws_region: "AWS region",
elevenlabs_model: "ElevenLabs model",
timeout: "Request timeout (seconds)",
max_retries: "Max retries",
},
toast: {
loadFailed: "Could not load AI settings",
saved: "AI provider settings saved",
savedDescription:
"Active providers updated. Changes apply to the next request.",
saveFailed: "Could not save settings",
testOk: "Provider chain ready",
testPartial: "Some providers missing credentials",
testFailed: "Provider test failed",
},
},
agents: {

View File

@@ -101,53 +101,11 @@ export function describeApiError(
const ACCESS_KEY = "encoach_token";
const REFRESH_KEY = "encoach_refresh_token";
const EXP_KEY = "encoach_token_exp";
const ENTITY_KEY = "encoach_entity_id";
function getAccessToken(): string | null {
return localStorage.getItem(ACCESS_KEY);
}
export function getActiveEntityId(): number | null {
try {
const raw = localStorage.getItem(ENTITY_KEY);
if (!raw) return null;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? n : null;
} catch {
return null;
}
}
export function setActiveEntityId(entityId: number | null | undefined): void {
try {
if (entityId && Number.isFinite(entityId)) {
localStorage.setItem(ENTITY_KEY, String(Math.floor(entityId)));
} else {
localStorage.removeItem(ENTITY_KEY);
}
} catch {
// ignore storage errors
}
}
/**
* Build a URL to a media-streaming endpoint with the JWT attached as a
* query parameter. Used by ``<img>`` / ``<audio>`` / ``<video>`` tags
* (which can't attach custom Authorization headers) and by ``<a download>``
* tags so the browser can fetch the binary directly without going through
* a fetch + blob URL dance.
*
* Returns the original path unchanged when no token is stored, which lets
* callers render a placeholder rather than crashing on ``null``.
*/
export function withAuthQuery(path: string): string {
if (!path) return path;
const token = getAccessToken();
if (!token) return path;
const sep = path.includes("?") ? "&" : "?";
return `${path}${sep}token=${encodeURIComponent(token)}`;
}
function getRefreshToken(): string | null {
return localStorage.getItem(REFRESH_KEY);
}
@@ -282,11 +240,6 @@ export type QueryParamValue =
*/
export type QueryParams = object;
const ENTITY_QUERY_SCOPE_RE =
/^\/(courses|students|teachers|batches|student\/my-courses|ai\/course-plan)(\/|$)/;
const ENTITY_BODY_SCOPE_RE =
/^\/(courses|students|teachers|batches|ai\/course-plan)(\/|$)/;
function buildUrl(path: string, params?: QueryParams): string {
const url = new URL(`${BASE_URL}${path}`, window.location.origin);
if (params) {
@@ -300,30 +253,9 @@ function buildUrl(path: string, params?: QueryParams): string {
url.searchParams.set(key, String(rawValue));
}
}
// Multi-entity LMS scope: when the user has selected an active entity
// in the UI, append it to entity-scoped endpoints unless the caller
// already provided an explicit entity_id.
const activeEntityId = getActiveEntityId();
if (
activeEntityId &&
!url.searchParams.has("entity_id") &&
ENTITY_QUERY_SCOPE_RE.test(path)
) {
url.searchParams.set("entity_id", String(activeEntityId));
}
return url.toString();
}
function maybeInjectEntityIntoBody(path: string, body: unknown): unknown {
const activeEntityId = getActiveEntityId();
if (!activeEntityId) return body;
if (!ENTITY_BODY_SCOPE_RE.test(path)) return body;
if (!body || typeof body !== "object" || Array.isArray(body)) return body;
const rec = body as Record<string, unknown>;
if (rec.entity_id !== undefined && rec.entity_id !== null) return body;
return { ...rec, entity_id: activeEntityId };
}
async function parseResponse<T>(response: Response): Promise<T> {
const data = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, response.statusText, data);
@@ -383,29 +315,26 @@ export const api = {
},
async post<T>(path: string, body?: unknown): Promise<T> {
const payload = maybeInjectEntityIntoBody(path, body);
return performRequest<T>(buildUrl(path), {
method: "POST",
headers: buildHeaders(),
body: payload ? JSON.stringify(payload) : undefined,
body: body ? JSON.stringify(body) : undefined,
});
},
async patch<T>(path: string, body?: unknown): Promise<T> {
const payload = maybeInjectEntityIntoBody(path, body);
return performRequest<T>(buildUrl(path), {
method: "PATCH",
headers: buildHeaders(),
body: payload ? JSON.stringify(payload) : undefined,
body: body ? JSON.stringify(body) : undefined,
});
},
async put<T>(path: string, body?: unknown): Promise<T> {
const payload = maybeInjectEntityIntoBody(path, body);
return performRequest<T>(buildUrl(path), {
method: "PUT",
headers: buildHeaders(),
body: payload ? JSON.stringify(payload) : undefined,
body: body ? JSON.stringify(body) : undefined,
});
},

View File

@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from "react";
import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
@@ -7,12 +7,10 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Search, Plus, Building2, Trash2, Pencil, Users, Shield, UserCog } from "lucide-react";
import { Search, Plus, Building2, Trash2, Pencil, Users, Shield } from "lucide-react";
import { entitiesService } from "@/services/entities.service";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { Checkbox } from "@/components/ui/checkbox";
import { useAuth } from "@/contexts/AuthContext";
const ENTITY_TYPES = [
{ value: "corporate", label: "Corporate" },
@@ -23,16 +21,10 @@ const ENTITY_TYPES = [
];
export default function EntitiesPage() {
const { user } = useAuth();
const isAdminUser = user?.user_type === "admin";
const [search, setSearch] = useState("");
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [editEntity, setEditEntity] = useState<{ id: number; name: string; code: string; type: string } | null>(null);
const [manageOpen, setManageOpen] = useState(false);
const [manageEntity, setManageEntity] = useState<{ id: number; name: string } | null>(null);
const [usersSearch, setUsersSearch] = useState("");
const [selectedUserIds, setSelectedUserIds] = useState<Set<number>>(new Set());
const [form, setForm] = useState({ name: "", code: "", type: "" });
const { toast } = useToast();
const qc = useQueryClient();
@@ -42,18 +34,6 @@ export default function EntitiesPage() {
queryFn: () => entitiesService.list({ size: 200 }),
});
const platformUsersQ = useQuery({
queryKey: ["platform-users-for-entities"],
queryFn: () => entitiesService.listPlatformUsers({ size: 500 }),
enabled: isAdminUser && manageOpen,
});
const entityUsersQ = useQuery({
queryKey: ["entity-users", manageEntity?.id],
queryFn: () => entitiesService.listEntityUsers(manageEntity!.id),
enabled: isAdminUser && !!manageEntity?.id,
});
const createMut = useMutation({
mutationFn: (data: { name: string; code?: string; type?: string }) =>
entitiesService.create(data as Partial<import("@/types").Entity>),
@@ -86,21 +66,6 @@ export default function EntitiesPage() {
onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
});
const saveEntityUsersMut = useMutation({
mutationFn: ({ entityId, userIds }: { entityId: number; userIds: number[] }) =>
entitiesService.updateEntityUsers(entityId, userIds),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["entities"] });
qc.invalidateQueries({ queryKey: ["entity-users"] });
setManageOpen(false);
setManageEntity(null);
setUsersSearch("");
setSelectedUserIds(new Set());
toast({ title: "Entity users updated" });
},
onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
});
const raw = entitiesQ.data as unknown;
const entities: { id: number; name: string; code: string; type: string; user_count: number; role_count: number; active: boolean }[] = (() => {
if (!raw) return [];
@@ -117,43 +82,11 @@ export default function EntitiesPage() {
);
const loading = entitiesQ.isLoading;
useEffect(() => {
if (!entityUsersQ.data) return;
setSelectedUserIds(new Set(entityUsersQ.data.map((u) => u.id)));
}, [entityUsersQ.data]);
const filteredPlatformUsers = useMemo(() => {
const all = platformUsersQ.data ?? [];
const q = usersSearch.trim().toLowerCase();
if (!q) return all;
return all.filter((u) =>
(u.name || "").toLowerCase().includes(q)
|| (u.email || "").toLowerCase().includes(q)
|| (u.login || "").toLowerCase().includes(q),
);
}, [platformUsersQ.data, usersSearch]);
function openEdit(e: typeof entities[0]) {
setEditEntity({ id: e.id, name: e.name, code: e.code, type: e.type });
setEditOpen(true);
}
function openManageUsers(e: typeof entities[0]) {
setManageEntity({ id: e.id, name: e.name });
setUsersSearch("");
setSelectedUserIds(new Set());
setManageOpen(true);
}
function toggleUser(userId: number) {
setSelectedUserIds((prev) => {
const next = new Set(prev);
if (next.has(userId)) next.delete(userId);
else next.add(userId);
return next;
});
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
@@ -226,11 +159,6 @@ export default function EntitiesPage() {
</TableCell>
<TableCell>
<div className="flex gap-1">
{isAdminUser ? (
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openManageUsers(e)}>
<UserCog className="h-4 w-4" />
</Button>
) : null}
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(e)}>
<Pencil className="h-4 w-4" />
</Button>
@@ -351,79 +279,6 @@ export default function EntitiesPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Manage Users Dialog (admin only) */}
<Dialog open={manageOpen} onOpenChange={(open) => {
setManageOpen(open);
if (!open) {
setManageEntity(null);
setUsersSearch("");
setSelectedUserIds(new Set());
}
}}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Manage Users {manageEntity?.name ?? ""}</DialogTitle>
</DialogHeader>
{!isAdminUser ? (
<div className="text-sm text-muted-foreground py-4">Only admin users can manage entity members.</div>
) : (
<div className="space-y-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search users by name/email/login..."
className="pl-9"
value={usersSearch}
onChange={(e) => setUsersSearch(e.target.value)}
/>
</div>
<div className="rounded-md border max-h-[420px] overflow-y-auto">
{platformUsersQ.isLoading || entityUsersQ.isLoading ? (
<div className="p-4 text-sm text-muted-foreground">Loading users...</div>
) : filteredPlatformUsers.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">No users found.</div>
) : (
<div className="divide-y">
{filteredPlatformUsers.map((u) => (
<label key={u.id} className="flex items-center gap-3 p-3 hover:bg-muted/40 cursor-pointer">
<Checkbox
checked={selectedUserIds.has(u.id)}
onCheckedChange={() => toggleUser(u.id)}
/>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{u.name || u.login || u.email}</div>
<div className="text-xs text-muted-foreground truncate">{u.email || u.login}</div>
</div>
</label>
))}
</div>
)}
</div>
</div>
)}
<DialogFooter>
<div className="text-xs text-muted-foreground mr-auto">
{selectedUserIds.size} user(s) selected
</div>
<Button variant="outline" onClick={() => setManageOpen(false)}>Cancel</Button>
<Button
disabled={!manageEntity || saveEntityUsersMut.isPending || !isAdminUser}
onClick={() => {
if (!manageEntity) return;
saveEntityUsersMut.mutate({
entityId: manageEntity.id,
userIds: Array.from(selectedUserIds),
});
}}
>
{saveEntityUsersMut.isPending ? "Saving..." : "Save Users"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -40,7 +40,6 @@ import {
useRenderAIPrompt,
} from "@/hooks/queries/useAIPrompts";
import { AIAgentsPanel } from "@/pages/admin/AIAgentsPanel";
import AIProviderSettings from "@/pages/admin/AIProviderSettings";
import { AIToolsPanel } from "@/pages/admin/AIToolsPanel";
import type { AIPromptSummary } from "@/types/ai-prompt";
import {
@@ -48,7 +47,6 @@ import {
CheckCircle2,
FileText,
History,
KeyRound,
Play,
PlusCircle,
Wrench,
@@ -584,13 +582,6 @@ export default function AIPromptEditor() {
<FileText className="me-1 h-4 w-4" />
{t("aiAdmin.tabs.prompts", "Prompts")}
</TabsTrigger>
<TabsTrigger
value="providers"
className="data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-md border px-4 py-2"
>
<KeyRound className="me-1 h-4 w-4" />
{t("aiAdmin.tabs.providers", "Providers & Keys")}
</TabsTrigger>
</TabsList>
<TabsContent value="agents" className="mt-2">
@@ -602,9 +593,6 @@ export default function AIPromptEditor() {
<TabsContent value="prompts" className="mt-2">
<AIPromptsPanel />
</TabsContent>
<TabsContent value="providers" className="mt-2">
<AIProviderSettings />
</TabsContent>
</Tabs>
</div>
);

View File

@@ -1,704 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
Activity,
CheckCircle2,
Eye,
EyeOff,
Image as ImageIcon,
Loader2,
Save,
Settings2,
Volume2,
Wand2,
XCircle,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import {
aiSettingsService,
type AISettingsPatchPayload,
type AISettingsState,
type CapabilityKey,
type CapabilityState,
type ProviderTestResult,
} from "@/services/aiSettings.service";
/**
* Admin UI for AI provider selection and API-key management.
*
* - Dropdowns set the active provider per capability (text / image / audio /
* video). Selecting "auto" tells the backend to try paid providers first
* and silently fall back to free providers on quota / billing errors.
* - API-key inputs are write-only — the backend never returns a key value;
* we only render a "saved" badge based on `keys_set[<name>]`.
* - Changes persist to `ir.config_parameter` and take effect on the very
* next request (no caching), so admins can flip OpenAI -> Mock without
* restarting Odoo.
*
* Mounted as the fourth tab on `/admin/ai/prompts` so the user keeps a
* single "AI" surface in the admin nav.
*/
const CAPABILITY_META: Array<{
key: CapabilityKey;
icon: React.ComponentType<{ className?: string }>;
i18nKey: string;
defaultLabel: string;
}> = [
{ key: "text", icon: Wand2, i18nKey: "aiProviders.cap.text", defaultLabel: "Text generation" },
{ key: "image", icon: ImageIcon, i18nKey: "aiProviders.cap.image", defaultLabel: "Image generation" },
{ key: "audio", icon: Volume2, i18nKey: "aiProviders.cap.audio", defaultLabel: "Audio (TTS)" },
{ key: "video", icon: Activity, i18nKey: "aiProviders.cap.video", defaultLabel: "Video composition" },
];
interface KeyFieldDef {
shortName: string;
i18nKey: string;
defaultLabel: string;
placeholder?: string;
hint?: string;
hintI18nKey?: string;
group: "openai" | "aws" | "elevenlabs" | "other" | "paymob";
}
const KEY_FIELDS: KeyFieldDef[] = [
// OpenAI
{
shortName: "openai_api_key",
i18nKey: "aiProviders.keys.openai",
defaultLabel: "OpenAI API key",
placeholder: "sk-…",
hintI18nKey: "aiProviders.keys.openai_hint",
hint: "Used for GPT-4o, embeddings, and DALL-E 3.",
group: "openai",
},
// AWS
{
shortName: "aws_access_key",
i18nKey: "aiProviders.keys.aws_access",
defaultLabel: "AWS Access Key ID",
placeholder: "AKIA…",
group: "aws",
},
{
shortName: "aws_secret_key",
i18nKey: "aiProviders.keys.aws_secret",
defaultLabel: "AWS Secret Access Key",
placeholder: "wJalr…",
group: "aws",
},
// ElevenLabs
{
shortName: "elevenlabs_api_key",
i18nKey: "aiProviders.keys.elevenlabs",
defaultLabel: "ElevenLabs API key",
placeholder: "el_…",
group: "elevenlabs",
},
// GPTZero
{
shortName: "gptzero_api_key",
i18nKey: "aiProviders.keys.gptzero",
defaultLabel: "GPTZero API key",
group: "other",
},
// Paymob (payments)
{
shortName: "paymob_api_key",
i18nKey: "aiProviders.keys.paymob_api",
defaultLabel: "Paymob API key",
group: "paymob",
},
{
shortName: "paymob_integration_id",
i18nKey: "aiProviders.keys.paymob_integration",
defaultLabel: "Paymob integration ID",
group: "paymob",
},
{
shortName: "paymob_iframe_id",
i18nKey: "aiProviders.keys.paymob_iframe",
defaultLabel: "Paymob iframe ID",
group: "paymob",
},
{
shortName: "paymob_hmac_secret",
i18nKey: "aiProviders.keys.paymob_hmac",
defaultLabel: "Paymob HMAC secret",
group: "paymob",
},
];
const KEY_GROUPS: Array<{
group: KeyFieldDef["group"];
i18nKey: string;
defaultLabel: string;
}> = [
{ group: "openai", i18nKey: "aiProviders.group.openai", defaultLabel: "OpenAI" },
{ group: "aws", i18nKey: "aiProviders.group.aws", defaultLabel: "AWS Polly" },
{ group: "elevenlabs", i18nKey: "aiProviders.group.elevenlabs", defaultLabel: "ElevenLabs" },
{ group: "other", i18nKey: "aiProviders.group.other", defaultLabel: "Other AI services" },
{ group: "paymob", i18nKey: "aiProviders.group.paymob", defaultLabel: "Paymob (payments)" },
];
const KIND_BADGE: Record<string, { className: string; labelKey: string; defaultLabel: string }> = {
paid: { className: "bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200",
labelKey: "aiProviders.kind.paid", defaultLabel: "Paid" },
free: { className: "bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200",
labelKey: "aiProviders.kind.free", defaultLabel: "Free" },
auto: { className: "bg-blue-100 text-blue-800 dark:bg-blue-950 dark:text-blue-200",
labelKey: "aiProviders.kind.auto", defaultLabel: "Auto" },
};
function CapabilityCard({
capKey,
state,
onChange,
onTest,
testing,
testResult,
}: {
capKey: CapabilityKey;
state: CapabilityState;
onChange: (newValue: string) => void;
onTest: () => void;
testing: boolean;
testResult: ProviderTestResult | null;
}) {
const { t } = useTranslation();
const meta = CAPABILITY_META.find((m) => m.key === capKey)!;
const Icon = meta.icon;
const activeOption = state.options.find((o) => o.value === state.active);
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between gap-2">
<CardTitle className="flex items-center gap-2 text-base">
<Icon className="h-4 w-4" />
{t(meta.i18nKey, meta.defaultLabel)}
</CardTitle>
{activeOption ? (
<Badge
variant="outline"
className={KIND_BADGE[activeOption.kind]?.className}
>
{t(
KIND_BADGE[activeOption.kind]?.labelKey ?? "aiProviders.kind.auto",
KIND_BADGE[activeOption.kind]?.defaultLabel ?? activeOption.kind,
)}
</Badge>
) : null}
</div>
<CardDescription>
{t(`${meta.i18nKey}_hint`, "Active provider for this capability.")}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="space-y-1">
<Label htmlFor={`provider-${capKey}`}>
{t("aiProviders.activeProvider", "Active provider")}
</Label>
<Select value={state.active} onValueChange={onChange}>
<SelectTrigger id={`provider-${capKey}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{state.options.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
<span className="flex items-center gap-2">
{opt.label}
<Badge
variant="outline"
className={`text-xs ${KIND_BADGE[opt.kind]?.className ?? ""}`}
>
{t(
KIND_BADGE[opt.kind]?.labelKey ?? "aiProviders.kind.auto",
KIND_BADGE[opt.kind]?.defaultLabel ?? opt.kind,
)}
</Badge>
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{state.paid_with_credentials.length === 0 && capKey !== "video" ? (
<p className="text-muted-foreground text-xs">
{t(
"aiProviders.noPaidKeys",
"No paid API keys configured for this capability — free fallback will be used.",
)}
</p>
) : (
<p className="text-muted-foreground text-xs">
{t("aiProviders.paidConfigured", "Configured paid providers:")}{" "}
{state.paid_with_credentials.join(", ") || "—"}
</p>
)}
<div className="flex items-center gap-2">
<Button
type="button"
variant="secondary"
size="sm"
onClick={onTest}
disabled={testing}
>
{testing ? (
<Loader2 className="me-1 h-3 w-3 animate-spin" />
) : null}
{t("aiProviders.testButton", "Test fallback chain")}
</Button>
{testResult ? (
<span className="text-muted-foreground text-xs">
{testResult.chain
.map((c) => `${c.provider}${c.ok ? " ✓" : " ✗"}`)
.join(" → ")}
</span>
) : null}
</div>
</CardContent>
</Card>
);
}
function SecretField({
field,
isSet,
value,
onChange,
onClear,
}: {
field: KeyFieldDef;
isSet: boolean;
value: string | undefined;
onChange: (v: string) => void;
onClear: () => void;
}) {
const { t } = useTranslation();
const [revealed, setRevealed] = useState(false);
const dirty = value !== undefined;
return (
<div className="space-y-1">
<div className="flex items-center justify-between gap-2">
<Label htmlFor={`key-${field.shortName}`} className="text-sm">
{t(field.i18nKey, field.defaultLabel)}
</Label>
<div className="flex items-center gap-2">
{isSet && !dirty ? (
<Badge
variant="outline"
className="bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200"
>
<CheckCircle2 className="me-1 h-3 w-3" />
{t("aiProviders.keys.saved", "Saved")}
</Badge>
) : null}
{dirty ? (
<Badge
variant="outline"
className="bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200"
>
{t("aiProviders.keys.unsaved", "Unsaved")}
</Badge>
) : null}
</div>
</div>
<div className="flex gap-2">
<div className="relative flex-1">
<Input
id={`key-${field.shortName}`}
type={revealed ? "text" : "password"}
placeholder={
isSet
? t("aiProviders.keys.placeholderSaved", "•••••• (click to replace)")
: (field.placeholder ?? "")
}
value={value ?? ""}
onChange={(e) => onChange(e.target.value)}
autoComplete="off"
spellCheck={false}
/>
<button
type="button"
onClick={() => setRevealed((v) => !v)}
className="text-muted-foreground hover:text-foreground absolute end-2 top-1/2 -translate-y-1/2"
tabIndex={-1}
aria-label={revealed ? "Hide value" : "Show value"}
>
{revealed ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
{isSet ? (
<Button
type="button"
variant="ghost"
size="sm"
onClick={onClear}
>
{t("aiProviders.keys.clear", "Clear")}
</Button>
) : null}
</div>
{field.hint ? (
<p className="text-muted-foreground text-xs">
{t(field.hintI18nKey ?? "", field.hint)}
</p>
) : null}
</div>
);
}
function PlainField({
shortName,
label,
value,
onChange,
}: {
shortName: string;
label: string;
value: string;
onChange: (v: string) => void;
}) {
return (
<div className="space-y-1">
<Label htmlFor={`plain-${shortName}`} className="text-sm">
{label}
</Label>
<Input
id={`plain-${shortName}`}
value={value}
onChange={(e) => onChange(e.target.value)}
/>
</div>
);
}
export default function AIProviderSettings() {
const { t } = useTranslation();
const [state, setState] = useState<AISettingsState | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Pending diff applied on Save. Provider edits are confirmed
// immediately so the UI reflects the active selection — but we still
// batch them into one PATCH so we don't burn requests on every click.
const [pendingProviders, setPendingProviders] = useState<
Partial<Record<CapabilityKey, string>>
>({});
const [pendingKeys, setPendingKeys] = useState<Record<string, string>>({});
const [pendingPlain, setPendingPlain] = useState<Record<string, string>>({});
const [testing, setTesting] = useState<CapabilityKey | null>(null);
const [testResults, setTestResults] = useState<
Partial<Record<CapabilityKey, ProviderTestResult>>
>({});
useEffect(() => {
void load();
}, []);
async function load() {
setLoading(true);
try {
const data = await aiSettingsService.get();
setState(data);
setPendingProviders({});
setPendingKeys({});
setPendingPlain({});
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
toast.error(t("aiProviders.toast.loadFailed", "Could not load AI settings"), {
description: msg,
});
} finally {
setLoading(false);
}
}
const dirty = useMemo(
() =>
Object.keys(pendingProviders).length > 0 ||
Object.keys(pendingKeys).length > 0 ||
Object.keys(pendingPlain).length > 0,
[pendingProviders, pendingKeys, pendingPlain],
);
async function handleSave() {
if (!state || !dirty) return;
setSaving(true);
try {
const payload: AISettingsPatchPayload = {};
if (Object.keys(pendingProviders).length) payload.providers = pendingProviders;
if (Object.keys(pendingKeys).length) payload.keys = pendingKeys;
if (Object.keys(pendingPlain).length) payload.plain = pendingPlain;
const updated = await aiSettingsService.update(payload);
setState(updated);
setPendingProviders({});
setPendingKeys({});
setPendingPlain({});
toast.success(
t("aiProviders.toast.saved", "AI provider settings saved"),
{
description: t(
"aiProviders.toast.savedDescription",
"Active providers updated. Changes apply to the next request.",
),
},
);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
toast.error(t("aiProviders.toast.saveFailed", "Could not save settings"), {
description: msg,
});
} finally {
setSaving(false);
}
}
async function handleTest(cap: CapabilityKey) {
setTesting(cap);
try {
const result = await aiSettingsService.test(cap);
setTestResults((prev) => ({ ...prev, [cap]: result }));
const allOk = result.chain.every((c) => c.ok);
if (allOk) {
toast.success(
t("aiProviders.toast.testOk", "Provider chain ready") +
` · ${result.chain.map((c) => c.provider).join(" → ")}`,
);
} else {
toast.warning(
t("aiProviders.toast.testPartial", "Some providers missing credentials") +
` · ${result.chain
.map((c) => `${c.provider}${c.ok ? "✓" : "✗"}`)
.join(" → ")}`,
);
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
toast.error(t("aiProviders.toast.testFailed", "Provider test failed"), {
description: msg,
});
} finally {
setTesting(null);
}
}
if (loading) {
return (
<div className="space-y-4">
<Skeleton className="h-32 w-full" />
<Skeleton className="h-64 w-full" />
</div>
);
}
if (!state) {
return (
<div className="text-muted-foreground py-12 text-center text-sm">
{t("aiProviders.empty", "Settings could not be loaded.")}
</div>
);
}
const effectiveProviders: Record<CapabilityKey, CapabilityState> = {
text: { ...state.providers.text, active: pendingProviders.text ?? state.providers.text.active },
image: { ...state.providers.image, active: pendingProviders.image ?? state.providers.image.active },
audio: { ...state.providers.audio, active: pendingProviders.audio ?? state.providers.audio.active },
video: { ...state.providers.video, active: pendingProviders.video ?? state.providers.video.active },
};
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<CardTitle className="flex items-center gap-2 text-lg">
<Settings2 className="h-5 w-5" />
{t("aiProviders.title", "AI Providers & API Keys")}
</CardTitle>
<CardDescription>
{t(
"aiProviders.subtitle",
"Pick the active provider per capability and store API keys. Changes take effect on the next request — no Odoo restart required.",
)}
</CardDescription>
</div>
<Button
onClick={handleSave}
disabled={!dirty || saving}
className="shrink-0"
>
{saving ? (
<Loader2 className="me-1 h-4 w-4 animate-spin" />
) : (
<Save className="me-1 h-4 w-4" />
)}
{t("aiProviders.save", "Save settings")}
</Button>
</div>
</CardHeader>
</Card>
<div className="grid gap-4 md:grid-cols-2">
{CAPABILITY_META.map((meta) => (
<CapabilityCard
key={meta.key}
capKey={meta.key}
state={effectiveProviders[meta.key]}
onChange={(newValue) =>
setPendingProviders((prev) => ({ ...prev, [meta.key]: newValue }))
}
onTest={() => handleTest(meta.key)}
testing={testing === meta.key}
testResult={testResults[meta.key] ?? null}
/>
))}
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">
{t("aiProviders.keys.title", "API keys")}
</CardTitle>
<CardDescription>
{t(
"aiProviders.keys.subtitle",
"Keys are write-only and stored encrypted at rest in ir.config_parameter. They are never returned to the browser.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{KEY_GROUPS.map((group) => {
const fields = KEY_FIELDS.filter((f) => f.group === group.group);
if (!fields.length) return null;
return (
<div key={group.group} className="space-y-3">
<h3 className="text-sm font-semibold">
{t(group.i18nKey, group.defaultLabel)}
</h3>
<div className="grid gap-4 md:grid-cols-2">
{fields.map((field) => (
<SecretField
key={field.shortName}
field={field}
isSet={Boolean(state.keys_set[field.shortName])}
value={pendingKeys[field.shortName]}
onChange={(v) =>
setPendingKeys((prev) => ({
...prev,
[field.shortName]: v,
}))
}
onClear={() =>
setPendingKeys((prev) => ({
...prev,
[field.shortName]: "",
}))
}
/>
))}
</div>
</div>
);
})}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">
{t("aiProviders.plain.title", "Model & runtime")}
</CardTitle>
<CardDescription>
{t(
"aiProviders.plain.subtitle",
"Non-secret runtime parameters: default model, AWS region, request timeout.",
)}
</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 md:grid-cols-2">
<PlainField
shortName="openai_model"
label={t("aiProviders.plain.openai_model", "OpenAI model")}
value={pendingPlain.openai_model ?? state.plain.openai_model ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, openai_model: v }))
}
/>
<PlainField
shortName="openai_fast_model"
label={t("aiProviders.plain.openai_fast", "OpenAI fast model")}
value={pendingPlain.openai_fast_model ?? state.plain.openai_fast_model ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, openai_fast_model: v }))
}
/>
<PlainField
shortName="aws_region"
label={t("aiProviders.plain.aws_region", "AWS region")}
value={pendingPlain.aws_region ?? state.plain.aws_region ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, aws_region: v }))
}
/>
<PlainField
shortName="elevenlabs_model"
label={t("aiProviders.plain.elevenlabs_model", "ElevenLabs model")}
value={pendingPlain.elevenlabs_model ?? state.plain.elevenlabs_model ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, elevenlabs_model: v }))
}
/>
<PlainField
shortName="request_timeout"
label={t("aiProviders.plain.timeout", "Request timeout (seconds)")}
value={pendingPlain.request_timeout ?? state.plain.request_timeout ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, request_timeout: v }))
}
/>
<PlainField
shortName="max_retries"
label={t("aiProviders.plain.max_retries", "Max retries")}
value={pendingPlain.max_retries ?? state.plain.max_retries ?? ""}
onChange={(v) =>
setPendingPlain((prev) => ({ ...prev, max_retries: v }))
}
/>
</CardContent>
</Card>
<p className="text-muted-foreground text-xs">
{t(
"aiProviders.footer",
"Provider settings are read fresh from ir.config_parameter on every request — no caching, no restart required.",
)}
</p>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -11,13 +11,13 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Upload, Search, FileText, Video, Link2, Download, Trash2,
CheckCircle2, Clock, XCircle, Loader2, BookOpen, Music, Image,
Tag, Plus, Pencil, X, CalendarDays, Eye,
Tag, Plus, Pencil, X, CalendarDays,
} 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 { describeApiError, withAuthQuery } from "@/lib/api-client";
import { describeApiError } from "@/lib/api-client";
import { useToast } from "@/hooks/use-toast";
import { TaxonomyCascade } from "@/components/TaxonomyCascade";
import type { Resource, ResourceTag } from "@/types";
@@ -165,13 +165,13 @@ function EditResourceDialog({
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="image">Image</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="article">Article</SelectItem>
<SelectItem value="link">Link</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="interactive">Interactive</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="image">Image</SelectItem>
<SelectItem value="article">Article</SelectItem>
</SelectContent>
</Select>
</div>
@@ -351,19 +351,12 @@ export default function ResourceManager() {
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="image">Image</SelectItem>
<SelectItem value="audio">Audio</SelectItem>
<SelectItem value="video">Video</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="article">Article</SelectItem>
<SelectItem value="link">Link</SelectItem>
<SelectItem value="document">Document</SelectItem>
<SelectItem value="interactive">Interactive</SelectItem>
</SelectContent>
</Select>
<p className="text-[11px] text-muted-foreground">
Tip: leave this on "PDF" the server auto-detects the
actual type from the uploaded file's MIME and corrects it.
</p>
</div>
<TaxonomyCascade
subjectId={uploadSubjectId} onSubjectChange={setUploadSubjectId}
@@ -626,46 +619,12 @@ function ContentTable({
<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 === "resource" && row.resourceId && row.raw && (
{row.source === "resource" && row.resourceId && (
<>
{/* Smart preview — opens the file inline (PDF in
iframe, image / audio / video in their native
tag) without forcing a download. ``link`` rows
jump to the external URL directly. */}
{(row.raw.preview_url || row.raw.url) && (
<Button
variant="ghost"
size="icon"
title="Preview"
onClick={() => {
const target =
row.raw?.preview_url
? withAuthQuery(row.raw.preview_url)
: row.raw?.url || "";
if (target) window.open(target, "_blank", "noopener,noreferrer");
}}
>
<Eye className="h-4 w-4" />
</Button>
)}
<Button variant="ghost" size="icon" title="Edit" onClick={() => row.raw && onEditResource(row.raw)}><Pencil className="h-4 w-4" /></Button>
{row.raw.has_file && (
<Button variant="ghost" size="icon" title="Download" onClick={async () => {
try {
const { blob, filename } = await resourcesService.download(row.resourceId!);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
// Prefer the server-provided filename (which always
// carries the extension) over ``row.name``, which
// is often just "test" — the previous behaviour
// saved files with no extension on disk.
a.download = filename || row.raw?.original_filename || row.raw?.file_name || 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="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={() => onDeleteResource(row.resourceId!)} disabled={deletePending}><Trash2 className="h-4 w-4 text-destructive" /></Button>
</>
)}

View File

@@ -1,20 +1,9 @@
import { useRef, useState } from "react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
FileText,
Image as ImageIcon,
Library,
Link2,
Mic,
Music,
Trash2,
Upload,
Video,
X,
} from "lucide-react";
import { X } from "lucide-react";
import { StepWizard, type WizardStepDef } from "@/components/wizard/StepWizard";
import { Input } from "@/components/ui/input";
@@ -29,10 +18,9 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { LibraryPickerDialog } from "@/components/coursePlan/LibraryPickerDialog";
import { coursePlanService } from "@/services/coursePlan.service";
import { describeApiError } from "@/lib/api-client";
import type { CoursePlanGenerateBrief, Resource } from "@/types";
import type { CoursePlanGenerateBrief } from "@/types";
/**
* AI course-plan generation wizard.
@@ -50,37 +38,6 @@ import type { CoursePlanGenerateBrief, Resource } from "@/types";
* materials immediately.
*/
type DraftSourceKind = "file" | "url" | "text" | "resource";
interface DraftSource {
/** Stable client-side id; not persisted. */
uid: string;
kind: DraftSourceKind;
name: string;
/** Only set when kind === "file". */
file?: File;
/** Only set when kind === "url". */
url?: string;
/** Only set when kind === "text". */
text?: string;
/** Only set when kind === "resource" — pointer into the central library. */
resourceId?: number;
/** Display-only metadata so we can render the row without a refetch. */
resourceType?: string;
}
interface MediaToggleState {
/** Generate narration audio (Polly / ElevenLabs) for listening +
* speaking materials right after each week's materials are produced. */
audio: boolean;
/** Generate DALL-E images for reading texts, listening scripts, and
* vocabulary lists. Bound to the per-plan image budget. */
image: boolean;
/** Compose audio + image into a slideshow MP4 with ffmpeg. Slowest
* option; off by default. */
video: boolean;
}
interface CoursePlanWizardState {
title: string;
cefr_level: string;
@@ -91,8 +48,6 @@ interface CoursePlanWizardState {
grammar_focus: string[];
resources: string[];
notes: string;
sources: DraftSource[];
media: MediaToggleState;
}
const CEFR_OPTIONS = [
@@ -228,17 +183,6 @@ export default function CoursePlanWizard() {
</div>
),
},
{
id: "sources",
titleKey: "coursePlan.wizard.steps.sources",
descriptionKey: "coursePlan.wizard.steps.sourcesDesc",
render: ({ state, update }) => (
<SourcesStep
sources={state.sources}
onChange={(sources) => update({ sources })}
/>
),
},
{
id: "scope",
titleKey: "coursePlan.wizard.steps.scope",
@@ -270,17 +214,6 @@ export default function CoursePlanWizard() {
</div>
),
},
{
id: "media",
titleKey: "coursePlan.wizard.steps.media",
descriptionKey: "coursePlan.wizard.steps.mediaDesc",
render: ({ state, update }) => (
<MediaStep
media={state.media}
onChange={(media) => update({ media })}
/>
),
},
{
id: "review",
titleKey: "coursePlan.wizard.steps.review",
@@ -324,26 +257,6 @@ export default function CoursePlanWizard() {
label={t("coursePlan.wizard.fields.notes")}
value={state.notes || "—"}
/>
<ReviewRow
label={t("coursePlan.wizard.steps.sources")}
value={
state.sources.length
? t("coursePlan.wizard.review.sourcesCount", {
count: state.sources.length,
})
: t("coursePlan.wizard.review.noSources")
}
/>
<ReviewRow
label={t("coursePlan.wizard.steps.media")}
value={[
state.media.audio ? t("coursePlan.media.audio") : null,
state.media.image ? t("coursePlan.media.image") : null,
state.media.video ? t("coursePlan.media.video") : null,
]
.filter(Boolean)
.join(", ") || t("coursePlan.wizard.review.mediaNone")}
/>
<div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
{t("coursePlan.wizard.reviewHint")}
</div>
@@ -370,11 +283,9 @@ export default function CoursePlanWizard() {
grammar_focus: [],
resources: [],
notes: "",
sources: [],
media: { audio: true, image: true, video: false },
}}
onFinish={async (state) => {
const resp = await mutation.mutateAsync({
await mutation.mutateAsync({
title: state.title.trim(),
cefr_level: state.cefr_level,
total_weeks: state.total_weeks,
@@ -387,368 +298,11 @@ export default function CoursePlanWizard() {
resources: state.resources.length ? state.resources : undefined,
notes: state.notes.trim() || undefined,
});
const planId = resp?.data?.id;
if (planId && state.sources.length) {
// Library picks go through the dedicated bulk endpoint — one
// round-trip for the whole set, with server-side dedupe — so we
// collect their ids first and post them together. The remaining
// file/url/text drafts are posted individually as before.
const resourceIds = state.sources
.filter((s) => s.kind === "resource" && s.resourceId)
.map((s) => s.resourceId as number);
if (resourceIds.length) {
try {
await coursePlanService.attachResources(planId, resourceIds);
} catch (err) {
toast.error(
describeApiError(
err,
t("coursePlan.sources.libraryAttachFailed"),
),
);
}
}
// Best-effort upload — we keep going even if a single one fails so
// the user lands on the detail page with whatever did make it in.
for (const src of state.sources) {
try {
if (src.kind === "file" && src.file) {
await coursePlanService.uploadSource(planId, src.file, {
name: src.name || src.file.name,
});
} else if (src.kind === "url" && src.url) {
await coursePlanService.createSource(planId, {
kind: "url",
url: src.url,
name: src.name || src.url,
});
} else if (src.kind === "text" && src.text) {
await coursePlanService.createSource(planId, {
kind: "text",
inline_text: src.text,
name: src.name || t("coursePlan.sourceKind.text"),
});
}
// src.kind === "resource" was already handled in the bulk
// attach above.
} catch (err) {
toast.error(
describeApiError(err, t("coursePlan.sources.uploadFailed", {
name: src.name || src.kind,
})),
);
}
}
}
}}
/>
);
}
function genUid() {
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
function SourcesStep({
sources,
onChange,
}: {
sources: DraftSource[];
onChange: (next: DraftSource[]) => void;
}) {
const { t } = useTranslation();
const fileRef = useRef<HTMLInputElement>(null);
const [draftUrl, setDraftUrl] = useState("");
const [draftText, setDraftText] = useState("");
const [libraryOpen, setLibraryOpen] = useState(false);
// Resource ids already queued in this wizard session; passed to the
// picker so the same resource can't be added twice.
const queuedResourceIds = new Set(
sources
.filter((s) => s.kind === "resource" && s.resourceId)
.map((s) => s.resourceId as number),
);
const addFiles = (files: FileList | null) => {
if (!files || !files.length) return;
const additions: DraftSource[] = [];
for (const f of Array.from(files)) {
additions.push({
uid: genUid(),
kind: "file",
name: f.name,
file: f,
});
}
onChange([...sources, ...additions]);
};
const addUrl = () => {
const url = draftUrl.trim();
if (!url) return;
onChange([...sources, { uid: genUid(), kind: "url", name: url, url }]);
setDraftUrl("");
};
const addText = () => {
const text = draftText.trim();
if (!text) return;
onChange([
...sources,
{
uid: genUid(),
kind: "text",
name: text.slice(0, 60).replace(/\s+/g, " "),
text,
},
]);
setDraftText("");
};
const addLibraryResources = (picked: Resource[]) => {
if (!picked.length) return;
const additions: DraftSource[] = picked.map((r) => ({
uid: genUid(),
kind: "resource",
name: r.name,
resourceId: r.id,
resourceType: r.resource_type || r.type || "resource",
}));
onChange([...sources, ...additions]);
setLibraryOpen(false);
};
const remove = (uid: string) => onChange(sources.filter((s) => s.uid !== uid));
return (
<div className="space-y-5">
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-md border-dashed border-2 px-4 py-6 text-center bg-muted/20">
<FileText className="mx-auto h-6 w-6 text-muted-foreground" />
<p className="mt-2 text-sm font-medium">
{t("coursePlan.sources.dropTitle")}
</p>
<p className="text-xs text-muted-foreground">
{t("coursePlan.sources.dropHint")}
</p>
<div className="mt-3">
<input
ref={fileRef}
type="file"
multiple
className="hidden"
accept=".pdf,.doc,.docx,.txt,.md,.html,.htm,.rtf"
onChange={(e) => {
addFiles(e.currentTarget.files);
if (fileRef.current) fileRef.current.value = "";
}}
/>
<Button
variant="outline"
size="sm"
onClick={() => fileRef.current?.click()}
>
<Upload className="mr-1 h-4 w-4" />
{t("coursePlan.sources.uploadFiles")}
</Button>
</div>
</div>
<div className="rounded-md border-dashed border-2 px-4 py-6 text-center bg-muted/20">
<Library className="mx-auto h-6 w-6 text-muted-foreground" />
<p className="mt-2 text-sm font-medium">
{t("coursePlan.sources.libraryPickTitle")}
</p>
<p className="text-xs text-muted-foreground">
{t("coursePlan.sources.libraryPickHint")}
</p>
<div className="mt-3">
<Button
variant="outline"
size="sm"
onClick={() => setLibraryOpen(true)}
>
<Library className="mr-1 h-4 w-4" />
{t("coursePlan.sources.libraryPickButton")}
</Button>
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<Label>{t("coursePlan.sources.urlLabel")}</Label>
<div className="mt-1 flex gap-2">
<Input
value={draftUrl}
onChange={(e) => setDraftUrl(e.target.value)}
placeholder="https://example.com/article"
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addUrl();
}
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addUrl}
disabled={!draftUrl.trim()}
>
<Link2 className="h-4 w-4" />
</Button>
</div>
</div>
<div>
<Label>{t("coursePlan.sources.textLabel")}</Label>
<div className="mt-1 flex gap-2">
<Textarea
rows={3}
value={draftText}
onChange={(e) => setDraftText(e.target.value)}
placeholder={t("coursePlan.sources.textPlaceholder")}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addText}
disabled={!draftText.trim()}
className="self-start"
>
<FileText className="h-4 w-4" />
</Button>
</div>
</div>
</div>
{sources.length > 0 && (
<div className="rounded-md border">
<div className="px-3 py-2 border-b bg-muted/30 text-xs uppercase tracking-wide text-muted-foreground">
{t("coursePlan.sources.collected", { count: sources.length })}
</div>
<ul className="divide-y">
{sources.map((s) => (
<li
key={s.uid}
className="flex items-center gap-2 px-3 py-2 text-sm"
>
<Badge variant="outline" className="capitalize text-[10px]">
{s.kind === "resource"
? s.resourceType || "library"
: s.kind}
</Badge>
{s.kind === "resource" && (
<Badge
variant="secondary"
className="gap-1 text-[10px] flex items-center"
>
<Library className="h-3 w-3" />
{t("coursePlan.sources.fromLibrary")}
</Badge>
)}
<span className="flex-1 truncate">{s.name}</span>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => remove(s.uid)}
aria-label={t("common.remove", "Remove")}
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
</div>
)}
<LibraryPickerDialog
open={libraryOpen}
onOpenChange={setLibraryOpen}
alreadyLinkedIds={queuedResourceIds}
onConfirm={addLibraryResources}
/>
</div>
);
}
function MediaStep({
media,
onChange,
}: {
media: MediaToggleState;
onChange: (next: MediaToggleState) => void;
}) {
const { t } = useTranslation();
return (
<div className="grid gap-3 sm:grid-cols-3">
<MediaToggleCard
icon={Music}
title={t("coursePlan.media.audioTitle")}
description={t("coursePlan.media.audioDesc")}
checked={media.audio}
onToggle={(v) => onChange({ ...media, audio: v })}
/>
<MediaToggleCard
icon={ImageIcon}
title={t("coursePlan.media.imageTitle")}
description={t("coursePlan.media.imageDesc")}
checked={media.image}
onToggle={(v) => onChange({ ...media, image: v })}
/>
<MediaToggleCard
icon={Video}
title={t("coursePlan.media.videoTitle")}
description={t("coursePlan.media.videoDesc")}
checked={media.video}
onToggle={(v) => onChange({ ...media, video: v })}
/>
<div className="sm:col-span-3 text-xs text-muted-foreground flex items-center gap-2">
<Mic className="h-3.5 w-3.5" />
{t("coursePlan.media.hint")}
</div>
</div>
);
}
function MediaToggleCard({
icon: Icon,
title,
description,
checked,
onToggle,
}: {
icon: typeof Music;
title: string;
description: string;
checked: boolean;
onToggle: (v: boolean) => void;
}) {
return (
<button
type="button"
onClick={() => onToggle(!checked)}
className={[
"rounded-md border p-3 text-left transition-colors",
checked
? "border-primary bg-primary/5"
: "border-border hover:bg-muted/40",
].join(" ")}
>
<div className="flex items-center gap-2">
<Icon className="h-4 w-4 text-primary" />
<div className="font-medium text-sm">{title}</div>
</div>
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
</button>
);
}
function ReviewRow({ label, value }: { label: string; value: string }) {
return (
<div className="grid grid-cols-3 gap-2">

View File

@@ -40,23 +40,10 @@ function buildAnswerMap(sections: ExamSessionSection[]) {
const map = new Map<number, ExamAnswer>();
for (const sec of sections) {
for (const q of sec.questions) {
// The backend `/api/exam/<id>/session` endpoint returns a
// `saved_answer` per question whenever a previous attempt is
// resumed (browser refresh, network drop, accidental tab-close).
// Seed the local map from that value so the student picks up
// exactly where they left off — without this, autosaved answers
// were silently dropped on every reload.
const saved = (q as unknown as { saved_answer?: unknown }).saved_answer;
const flagged = Boolean(
(q as unknown as { flagged?: boolean }).flagged,
);
map.set(q.id, {
question_id: q.id,
answer:
saved === undefined || saved === null
? null
: (saved as ExamAnswer["answer"]),
flagged,
answer: null,
flagged: false,
time_spent_ms: 0,
});
}

View File

@@ -1,347 +0,0 @@
import { useMemo, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
ArrowLeft,
BookOpen,
Calendar,
ClipboardList,
Headphones,
Image as ImageIcon,
Library,
MessageSquare,
Mic,
Music,
PenSquare,
Sparkles,
Type,
Video,
type LucideIcon,
} from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { coursePlanService } from "@/services/coursePlan.service";
import { describeApiError, withAuthQuery } from "@/lib/api-client";
import MaterialBookView, { SkillBadge } from "@/components/coursePlan/MaterialBookView";
import type {
CoursePlan,
CoursePlanMaterial,
CoursePlanMedia,
CoursePlanWeek,
} from "@/types";
const SKILL_ICONS: Record<string, LucideIcon> = {
reading: BookOpen,
writing: PenSquare,
listening: Headphones,
speaking: Mic,
grammar: Type,
vocabulary: Library,
integrated: MessageSquare,
};
/**
* Student detail view for an assigned AI course plan.
*
* Server-side authorisation: the `/api/student/course-plans/:id` endpoint
* returns 403 unless the current user is in the plan's assignment list,
* so we can render unconditionally as soon as the query resolves.
*
* The page is intentionally read-only — students can play audio, view
* images, and watch video, but they can't (re)generate content.
*/
export default function StudentCoursePlanDetail() {
const { t } = useTranslation();
const { planId: planIdRaw } = useParams<{ planId: string }>();
const planId = Number(planIdRaw);
const { data, isLoading, isError, error } = useQuery({
queryKey: ["student-course-plan", planId],
queryFn: () => coursePlanService.studentGet(planId),
enabled: Number.isFinite(planId) && planId > 0,
});
const plan = data?.data as CoursePlan | undefined;
const materialsByWeek = useMemo(() => {
const map = new Map<number, CoursePlanMaterial[]>();
if (!plan?.materials) return map;
for (const m of plan.materials) {
const list = map.get(m.week_number) ?? [];
list.push(m);
map.set(m.week_number, list);
}
return map;
}, [plan?.materials]);
return (
<div className="space-y-6">
<Button variant="ghost" size="sm" asChild className="-ml-2 text-muted-foreground">
<Link to="/student/course-plans" className="flex items-center gap-1">
<ArrowLeft className="h-4 w-4" />
{t("coursePlan.student.backToList")}
</Link>
</Button>
{isLoading && (
<div className="space-y-3">
<Skeleton className="h-20" />
<Skeleton className="h-40" />
<Skeleton className="h-40" />
</div>
)}
{isError && (
<div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
{describeApiError(error, t("coursePlan.loadFailed"))}
</div>
)}
{plan && (
<>
<Card>
<CardHeader>
<div className="flex items-start justify-between gap-3 flex-wrap">
<div className="flex-1 min-w-0">
<CardTitle className="text-2xl">{plan.name}</CardTitle>
{plan.description && (
<CardDescription className="max-w-3xl">
{plan.description}
</CardDescription>
)}
</div>
<div className="flex gap-2 flex-wrap">
<Badge variant="secondary" className="uppercase">
{plan.cefr_level}
</Badge>
<Badge variant="outline">
{t("coursePlan.weeksCount", { count: plan.total_weeks })}
</Badge>
<Badge variant="outline">
{t("coursePlan.hoursPerWeek", {
count: plan.contact_hours_per_week,
})}
</Badge>
</div>
</div>
{plan.assignment && (
<p className="text-xs text-muted-foreground flex items-center gap-1.5">
<Calendar className="h-3.5 w-3.5" />
{plan.assignment.due_date
? t("coursePlan.student.due", { date: plan.assignment.due_date })
: t("coursePlan.student.noDue")}
{plan.assignment.assigned_by_name && (
<span>
·{" "}
{t("coursePlan.student.assignedBy", {
name: plan.assignment.assigned_by_name,
})}
</span>
)}
</p>
)}
{plan.assignment?.message && (
<p className="text-sm bg-muted/40 rounded-md px-3 py-2 mt-2">
{plan.assignment.message}
</p>
)}
</CardHeader>
</Card>
{plan.objectives.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<ClipboardList className="h-4 w-4 text-primary" />
{t("coursePlan.sections.objectives")}
</CardTitle>
</CardHeader>
<CardContent>
<ol className="list-decimal list-inside space-y-1 text-sm">
{plan.objectives.map((o, i) => (
<li key={i}>{o}</li>
))}
</ol>
</CardContent>
</Card>
)}
{plan.weeks && plan.weeks.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Sparkles className="h-4 w-4 text-primary" />
{t("coursePlan.sections.delivery")}
</CardTitle>
<CardDescription>{t("coursePlan.deliveryHint")}</CardDescription>
</CardHeader>
<CardContent>
<Accordion type="multiple" className="w-full">
{plan.weeks.map((w) => (
<StudentWeek
key={w.id}
week={w}
materials={materialsByWeek.get(w.week_number) ?? []}
/>
))}
</Accordion>
</CardContent>
</Card>
)}
</>
)}
</div>
);
}
function StudentWeek({
week,
materials,
}: {
week: CoursePlanWeek;
materials: CoursePlanMaterial[];
}) {
const { t } = useTranslation();
const [skillFilter, setSkillFilter] = useState<string>("all");
const skills = useMemo(
() => Array.from(new Set(materials.map((m) => m.skill))).sort(),
[materials],
);
const filteredMaterials = useMemo(
() => materials.filter((m) => skillFilter === "all" || m.skill === skillFilter),
[materials, skillFilter],
);
return (
<AccordionItem value={String(week.week_number)}>
<AccordionTrigger className="text-left">
<div className="flex-1 flex items-center gap-3 min-w-0">
<Badge variant="outline" className="shrink-0">
{t("coursePlan.weekN", { n: week.week_number })}
</Badge>
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{week.focus || week.unit || "—"}
</div>
{week.date_label && (
<div className="text-xs text-muted-foreground truncate">
{week.date_label}
</div>
)}
</div>
</div>
</AccordionTrigger>
<AccordionContent className="space-y-3">
{skills.length > 0 && (
<div className="flex items-center gap-1 flex-wrap">
<Button
size="sm"
variant={skillFilter === "all" ? "default" : "outline"}
onClick={() => setSkillFilter("all")}
>
{t("common.all", "All")}
</Button>
{skills.map((s) => (
<Button
key={s}
size="sm"
variant={skillFilter === s ? "default" : "outline"}
onClick={() => setSkillFilter(s)}
className="capitalize"
>
{s}
</Button>
))}
</div>
)}
{materials.length === 0 && (
<p className="text-sm italic text-muted-foreground">
{t("coursePlan.media.noMedia")}
</p>
)}
{filteredMaterials.map((m) => (
<StudentMaterial key={m.id} material={m} />
))}
</AccordionContent>
</AccordionItem>
);
}
function StudentMaterial({ material }: { material: CoursePlanMaterial }) {
const { t } = useTranslation();
const Icon = SKILL_ICONS[material.skill] ?? ClipboardList;
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center gap-2 flex-wrap">
<Icon className="h-4 w-4 text-primary" />
<CardTitle className="text-base flex-1 min-w-0">
{material.title}
</CardTitle>
<Badge variant="outline" className="text-[10px]">
{t(
`coursePlan.materialType.${material.material_type}`,
material.material_type,
)}
</Badge>
<SkillBadge skill={material.skill} />
</div>
{material.summary && <CardDescription>{material.summary}</CardDescription>}
{material.share_date && (
<CardDescription>
{t("coursePlan.shareDate", "Share date")}: {material.share_date}
</CardDescription>
)}
</CardHeader>
<CardContent className="space-y-3">
{(material.media ?? []).map((m) => (
<StudentMediaTile key={m.id} media={m} />
))}
<MaterialBookView material={material} />
</CardContent>
</Card>
);
}
function StudentMediaTile({ media }: { media: CoursePlanMedia }) {
const url = withAuthQuery(media.preview_url || media.download_url || "");
if (!url) return null;
return (
<div className="rounded-md border bg-muted/20 p-2 space-y-2">
<div className="flex items-center gap-2">
{media.kind === "audio" && <Music className="h-4 w-4" />}
{media.kind === "image" && <ImageIcon className="h-4 w-4" />}
{media.kind === "video" && <Video className="h-4 w-4" />}
<span className="capitalize text-xs text-muted-foreground">
{media.kind}
</span>
</div>
{media.kind === "audio" && <audio src={url} controls className="w-full" />}
{media.kind === "image" && (
<img
src={url}
alt={media.title}
className="w-full rounded-md max-h-72 object-contain bg-muted/30"
/>
)}
{media.kind === "video" && (
<video src={url} controls className="w-full rounded-md max-h-72" />
)}
</div>
);
}

View File

@@ -1,147 +0,0 @@
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
ArrowRight,
Calendar,
GraduationCap,
Sparkles,
} from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { coursePlanService } from "@/services/coursePlan.service";
import { describeApiError } from "@/lib/api-client";
import type { CoursePlan } from "@/types";
/**
* Student-facing list of AI course plans assigned to the current user.
*
* Reads from `GET /api/student/course-plans`, which only returns plans
* the user has been linked to either directly (Phase D `students` mode)
* or via the batch they're enrolled in. The card itself is intentionally
* lightweight: tap → drill into `/student/course-plans/:id` for the full
* weekly plan and embedded media.
*/
export default function StudentCoursePlans() {
const { t } = useTranslation();
const { data, isLoading, isError, error } = useQuery({
queryKey: ["student-course-plans"],
queryFn: () => coursePlanService.studentList(),
});
const items = data?.items ?? [];
return (
<div className="space-y-6">
<div>
<div className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-primary" />
<h1 className="text-2xl font-bold">{t("coursePlan.student.listTitle")}</h1>
</div>
<p className="text-muted-foreground mt-1 max-w-2xl">
{t("coursePlan.student.listSubtitle")}
</p>
</div>
{isLoading && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="h-44 rounded-lg" />
))}
</div>
)}
{isError && (
<div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
{describeApiError(error, t("coursePlan.loadFailed"))}
</div>
)}
{!isLoading && !isError && items.length === 0 && (
<div className="text-center py-12 border rounded-lg bg-muted/20">
<GraduationCap className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
<p className="text-muted-foreground">
{t("coursePlan.student.empty")}
</p>
</div>
)}
{items.length > 0 && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{items.map((plan) => (
<PlanCard key={plan.id} plan={plan} />
))}
</div>
)}
</div>
);
}
function PlanCard({ plan }: { plan: CoursePlan }) {
const { t } = useTranslation();
const a = plan.assignment;
return (
<Card className="hover:shadow-md transition-shadow flex flex-col">
<CardHeader>
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-base flex-1 min-w-0 line-clamp-2">
{plan.name}
</CardTitle>
<Badge variant="secondary" className="uppercase shrink-0">
{plan.cefr_level}
</Badge>
</div>
{plan.description && (
<CardDescription className="line-clamp-2">
{plan.description}
</CardDescription>
)}
</CardHeader>
<CardContent className="flex-1 flex flex-col gap-3">
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline">
{t("coursePlan.weeksCount", { count: plan.total_weeks })}
</Badge>
<Badge variant="outline">
{t("coursePlan.hoursPerWeek", {
count: plan.contact_hours_per_week,
})}
</Badge>
</div>
{a && (
<div className="text-xs text-muted-foreground space-y-0.5">
{a.assigned_by_name && (
<div>
{t("coursePlan.student.assignedBy", { name: a.assigned_by_name })}
</div>
)}
<div className="flex items-center gap-1">
<Calendar className="h-3 w-3" />
{a.due_date
? t("coursePlan.student.due", { date: a.due_date })
: t("coursePlan.student.noDue")}
</div>
</div>
)}
<div className="mt-auto pt-2">
<Button asChild size="sm" className="w-full">
<Link to={`/student/course-plans/${plan.id}`}>
{t("coursePlan.student.open")}
<ArrowRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>
</CardContent>
</Card>
);
}

View File

@@ -440,9 +440,9 @@ function ResourceTable({
<>
<Button variant="ghost" size="icon" title="Download" onClick={async () => {
try {
const { blob, filename } = await resourcesService.download(row.resourceId!);
const blob = await resourcesService.download(row.resourceId!);
const url = URL.createObjectURL(blob); const a = document.createElement("a");
a.href = url; a.download = filename || row.name || "resource"; a.click(); URL.revokeObjectURL(url);
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" />

View File

@@ -1,82 +0,0 @@
import { api } from "@/lib/api-client";
/**
* AI provider & API-key settings client.
*
* Backed by `backend/custom_addons/encoach_ai/controllers/ai_settings_controller.py`
* (`/api/ai/settings/providers`). API keys are write-only — the GET response
* only ever exposes `<key>_set: boolean` markers, never the key itself.
*
* Provider switches take effect on the very next request (no caching),
* so the LangGraph runtime instantly picks up the new selection.
*/
export type CapabilityKey = "text" | "image" | "audio" | "video";
export type ProviderKind = "paid" | "free" | "auto";
export interface ProviderOption {
value: string;
label: string;
kind: ProviderKind;
}
export interface CapabilityState {
active: string;
options: ProviderOption[];
paid_with_credentials: string[];
}
export interface AISettingsState {
providers: Record<CapabilityKey, CapabilityState>;
/** Boolean markers — `true` means a value is stored, never the value itself. */
keys_set: Record<string, boolean>;
/** Plain (non-secret) parameters, e.g. region, model name. */
plain: Record<string, string>;
}
export interface ProviderTestResult {
capability: CapabilityKey;
active: string;
chain: { provider: string; ok: boolean; note: string }[];
}
export interface AISettingsPatchPayload {
/** Active provider per capability. */
providers?: Partial<Record<CapabilityKey, string>>;
/**
* API keys keyed by short name (`openai_api_key`, `aws_access_key`,
* `aws_secret_key`, `aws_region`, `elevenlabs_api_key`,
* `gptzero_api_key`, `paymob_api_key`, `paymob_integration_id`,
* `paymob_iframe_id`, `paymob_hmac_secret`).
*
* - Sending an empty string clears the key.
* - Omitting the field leaves it unchanged.
*/
keys?: Record<string, string>;
/** Plain (non-secret) values like `aws_region`, `openai_model`. */
plain?: Record<string, string>;
}
export const aiSettingsService = {
async get(): Promise<AISettingsState> {
const resp = await api.get<{ data: AISettingsState }>(
"/ai/settings/providers",
);
return resp.data;
},
async update(payload: AISettingsPatchPayload): Promise<AISettingsState> {
const resp = await api.patch<{ data: AISettingsState }>(
"/ai/settings/providers",
payload,
);
return resp.data;
},
async test(capability: CapabilityKey): Promise<ProviderTestResult> {
return api.post<ProviderTestResult>(
"/ai/settings/providers/test",
{ capability },
);
},
};

View File

@@ -1,13 +1,8 @@
import { api } from "@/lib/api-client";
import type {
CoursePlan,
CoursePlanAssignment,
CoursePlanDeliverables,
CoursePlanGenerateBrief,
CoursePlanMaterial,
CoursePlanMedia,
CoursePlanSource,
CoursePlanSourceKind,
} from "@/types";
/**
@@ -17,9 +12,6 @@ import type {
* `backend/custom_addons/encoach_ai_course/controllers/course_plan.py`.
*/
export const coursePlanService = {
// ---------------------------------------------------------------------
// Plan lifecycle
// ---------------------------------------------------------------------
async list(params?: {
page?: number;
size?: number;
@@ -53,208 +45,4 @@ export const coursePlanService = {
): Promise<{ items: CoursePlanMaterial[]; count: number }> {
return api.get(`/ai/course-plan/${planId}/weeks/${weekNumber}/materials`);
},
async updateMaterial(
materialId: number,
payload: {
title?: string;
summary?: string;
body?: Record<string, unknown>;
body_text?: string;
share_date?: string | null;
is_static?: boolean;
},
): Promise<{ data: CoursePlanMaterial }> {
return api.patch(`/ai/course-plan/material/${materialId}`, payload);
},
// ---------------------------------------------------------------------
// Phase A — Sources
// ---------------------------------------------------------------------
async listSources(planId: number): Promise<{ items: CoursePlanSource[]; count: number }> {
return api.get(`/ai/course-plan/${planId}/sources`);
},
async createSource(
planId: number,
payload:
| { kind: "url"; url: string; name?: string; auto_index?: boolean }
| { kind: "text"; inline_text: string; name?: string; auto_index?: boolean },
): Promise<{ data: CoursePlanSource }> {
return api.post(`/ai/course-plan/${planId}/sources`, payload);
},
async uploadSource(
planId: number,
file: File,
opts?: { name?: string; auto_index?: boolean },
): Promise<{ data: CoursePlanSource }> {
const fd = new FormData();
fd.append("file", file);
fd.append("kind", "file" satisfies CoursePlanSourceKind);
if (opts?.name) fd.append("name", opts.name);
if (opts?.auto_index !== undefined) {
fd.append("auto_index", opts.auto_index ? "1" : "0");
}
return api.upload(`/ai/course-plan/${planId}/sources`, fd);
},
async reindexSource(
planId: number,
sourceId: number,
): Promise<{ data: CoursePlanSource }> {
return api.post(
`/ai/course-plan/${planId}/sources/${sourceId}/index`,
);
},
async deleteSource(
planId: number,
sourceId: number,
): Promise<{ success: boolean }> {
return api.delete(`/ai/course-plan/${planId}/sources/${sourceId}`);
},
/**
* Attach existing items from /admin/resources to a course plan as RAG
* sources. Returns the rows that were newly attached plus the ids
* that were skipped (already linked) or missing (deleted from the
* library) so the caller can show a clear toast — e.g. "Attached 2,
* skipped 1 already-linked".
*/
async attachResources(
planId: number,
resourceIds: number[],
): Promise<{
attached: CoursePlanSource[];
skipped_existing: number[];
missing: number[];
count: number;
}> {
return api.post(
`/ai/course-plan/${planId}/sources/from-resources`,
{ resource_ids: resourceIds },
);
},
// ---------------------------------------------------------------------
// Phase B — Deliverables / progress
// ---------------------------------------------------------------------
async deliverables(planId: number): Promise<CoursePlanDeliverables> {
return api.get(`/ai/course-plan/${planId}/deliverables`);
},
// ---------------------------------------------------------------------
// Phase C — Multimedia
// ---------------------------------------------------------------------
async listMaterialMedia(
materialId: number,
): Promise<{ items: CoursePlanMedia[]; count: number }> {
return api.get(`/ai/course-plan/material/${materialId}/media`);
},
async generateAudio(
materialId: number,
payload?: {
voice?: string;
language?: string;
gender?: "male" | "female";
provider?: "polly" | "elevenlabs";
},
): Promise<{ data: CoursePlanMedia }> {
return api.post(
`/ai/course-plan/material/${materialId}/media/audio`,
payload ?? {},
);
},
async generateImage(
materialId: number,
payload?: {
prompt?: string;
size?: "1024x1024" | "1792x1024" | "1024x1792";
style?: "natural" | "vivid";
quality?: "standard" | "hd";
},
): Promise<{ data: CoursePlanMedia }> {
return api.post(
`/ai/course-plan/material/${materialId}/media/image`,
payload ?? {},
);
},
async composeVideo(materialId: number): Promise<{ data: CoursePlanMedia }> {
return api.post(
`/ai/course-plan/material/${materialId}/media/video`,
);
},
async deleteMedia(mediaId: number): Promise<{ success: boolean }> {
return api.delete(`/ai/course-plan/media/${mediaId}`);
},
async generateWeekMedia(
planId: number,
weekNumber: number,
payload?: { kinds?: Array<"audio" | "image" | "video"> },
): Promise<{ items: Array<CoursePlanMedia | { error: string; material_id: number }>; count: number }> {
return api.post(
`/ai/course-plan/${planId}/weeks/${weekNumber}/media`,
payload ?? {},
);
},
// ---------------------------------------------------------------------
// Phase D — Assignments
// ---------------------------------------------------------------------
async listAssignments(
planId: number,
): Promise<{ items: CoursePlanAssignment[]; count: number }> {
return api.get(`/ai/course-plan/${planId}/assignments`);
},
async createAssignment(
planId: number,
payload:
| {
mode: "batch";
batch_id: number;
due_date?: string | null;
message?: string;
}
| {
mode: "students";
student_user_ids: number[];
due_date?: string | null;
message?: string;
}
| {
mode: "entities";
entity_ids: number[];
due_date?: string | null;
message?: string;
},
): Promise<{ data: CoursePlanAssignment }> {
return api.post(`/ai/course-plan/${planId}/assignments`, payload);
},
async deleteAssignment(
planId: number,
assignmentId: number,
): Promise<{ success: boolean }> {
return api.delete(
`/ai/course-plan/${planId}/assignments/${assignmentId}`,
);
},
// ---------------------------------------------------------------------
// Phase E — Student-side
// ---------------------------------------------------------------------
async studentList(): Promise<{ items: CoursePlan[]; count: number }> {
return api.get("/student/course-plans");
},
async studentGet(planId: number): Promise<{ data: CoursePlan }> {
return api.get(`/student/course-plans/${planId}`);
},
};

View File

@@ -2,14 +2,6 @@ import { api } from "@/lib/api-client";
import { asPaginated, asRecordData } from "@/lib/odoo-api";
import type { Entity, EntityRole, PaginatedResponse, PaginationParams, ApiSuccessResponse } from "@/types";
export interface EntityUser {
id: number;
name: string;
login: string;
email: string;
active: boolean;
}
export const entitiesService = {
async list(params?: PaginationParams): Promise<PaginatedResponse<Entity>> {
const raw = await api.get<unknown>("/entities", params as Record<string, string | number | boolean | undefined>);
@@ -50,20 +42,4 @@ export const entitiesService = {
async getPermissions(entityId: number): Promise<string[]> {
return api.get<string[]>(`/permissions`, { entity_id: entityId });
},
async listEntityUsers(entityId: number): Promise<EntityUser[]> {
const raw = await api.get<unknown>(`/entities/${entityId}/users`);
const out = asPaginated<EntityUser>(raw);
return out.items;
},
async updateEntityUsers(entityId: number, userIds: number[]): Promise<ApiSuccessResponse> {
return api.patch<ApiSuccessResponse>(`/entities/${entityId}/users`, { user_ids: userIds });
},
async listPlatformUsers(params?: PaginationParams): Promise<EntityUser[]> {
const raw = await api.get<unknown>("/users/list", params as Record<string, string | number | boolean | undefined>);
const out = asPaginated<EntityUser>(raw);
return out.items;
},
};

View File

@@ -42,27 +42,12 @@ export const resourcesService = {
return api.post<ApiSuccessResponse>(`/resources/${id}/rate`, { rating });
},
/**
* Downloads the binary and returns the blob alongside the filename
* the server suggested via ``Content-Disposition``. Callers should
* prefer that filename over the human ``name`` on the record so the
* extension is preserved (".pdf" / ".mp3" / ".png" etc.) — the
* legacy code dropped the extension because the human name was just
* "test".
*/
async download(id: number): Promise<{ blob: Blob; filename: string }> {
async download(id: number): Promise<Blob> {
const res = await fetch(`${API_BASE_URL}/resources/${id}/download`, {
headers: { Authorization: `Bearer ${localStorage.getItem("encoach_token") ?? ""}` },
});
if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText}`);
const cd = res.headers.get("content-disposition") || "";
let filename = "";
// Match either ``filename*=UTF-8''…`` (RFC 5987) or ``filename="…"``
const match =
/filename\*\s*=\s*[^']*''([^;]+)/i.exec(cd) ||
/filename\s*=\s*"?([^";]+)"?/i.exec(cd);
if (match) filename = decodeURIComponent(match[1].trim());
return { blob: await res.blob(), filename };
return res.blob();
},
// Tag management

View File

@@ -61,24 +61,8 @@ export interface Resource {
id: number;
name: string;
type?: string;
resource_type:
| "pdf"
| "video"
| "link"
| "document"
| "interactive"
| "audio"
| "image"
| "article";
resource_type: "pdf" | "video" | "link" | "document" | "interactive";
url?: string;
/** Authenticated REST URL for forced download (Content-Disposition: attachment). */
download_url?: string;
/** Authenticated REST URL for inline preview (Content-Disposition: inline). */
preview_url?: string;
/** Cached MIME type from upload — drives the right preview widget. */
mimetype?: string;
/** Filename as uploaded, including extension. */
original_filename?: string;
file_name?: string;
subject_id?: number | null;
subject_name?: string;

View File

@@ -77,177 +77,15 @@ export interface CoursePlanMaterial {
skill: string;
material_type: CoursePlanMaterialType | string;
title: string;
is_static?: boolean;
share_date?: string | null;
summary: string;
/** Loose shape: depends on material_type. */
body: Record<string, unknown>;
body_text: string;
media?: CoursePlanMedia[];
}
// ---------------------------------------------------------------------------
// Phase A — Reference sources
// ---------------------------------------------------------------------------
export type CoursePlanSourceKind = "file" | "url" | "text" | "resource";
export type CoursePlanSourceStatus = "pending" | "indexing" | "indexed" | "failed";
export interface CoursePlanSource {
id: number;
plan_id: number;
name: string;
kind: CoursePlanSourceKind;
file_name: string;
mime_type: string;
url: string;
has_inline_text: boolean;
/** Set when the source is linked to an item from /admin/resources. */
resource_id?: number | null;
resource_name?: string;
resource_type?: string;
status: CoursePlanSourceStatus;
error: string;
chunks_count: number;
extracted_chars: number;
indexed_at: string | null;
created_at: string | null;
}
// ---------------------------------------------------------------------------
// Phase B — Deliverables preview / progress
// ---------------------------------------------------------------------------
export type DeliverableStatus = "planned" | "generated" | "ready";
export interface CoursePlanDeliverable {
skill: string;
material_type: string;
material_id: number | null;
title: string;
status: DeliverableStatus;
media: Array<{
id: number;
kind: "audio" | "image" | "video";
status: string;
provider: string;
}>;
}
export interface CoursePlanDeliverablesWeek {
week_number: number;
date_label: string;
unit: string;
focus: string;
items_total: number;
deliverables: CoursePlanDeliverable[];
}
export interface CoursePlanDeliverables {
summary: {
total: number;
planned: number;
generated: number;
ready: number;
percent_ready: number;
media: {
audio: number;
image: number;
video: number;
audio_ready: number;
image_ready: number;
video_ready: number;
};
};
weeks: CoursePlanDeliverablesWeek[];
}
// ---------------------------------------------------------------------------
// Phase C — Multimedia
// ---------------------------------------------------------------------------
export type CoursePlanMediaKind = "audio" | "image" | "video";
export type CoursePlanMediaStatus = "queued" | "generating" | "ready" | "failed";
export type CoursePlanMediaProvider =
| "polly"
| "elevenlabs"
| "openai_image"
| "ffmpeg"
| "elai"
// Free fallbacks (Phase 24.1)
| "pillow"
| "unsplash"
| "gtts"
| "silent"
| "static"
| "mock"
| "auto"
| "manual";
export interface CoursePlanMedia {
id: number;
plan_id: number;
week_id: number | null;
material_id: number | null;
kind: CoursePlanMediaKind;
provider: CoursePlanMediaProvider | string;
title: string;
voice: string;
language: string;
style: string;
mime_type: string;
size_bytes: number;
duration_seconds: number;
width: number;
height: number;
attachment_id: number | null;
/** REST URL with ``Content-Disposition: attachment`` — used by the
* download buttons. The frontend appends ``?token=<jwt>`` so it works
* from plain ``<a download>`` tags. */
download_url: string;
/** REST URL with ``Content-Disposition: inline`` — used as the ``src``
* for ``<img>`` / ``<audio>`` / ``<video>`` tags. The frontend appends
* ``?token=<jwt>`` because browsers can't attach custom headers to
* these element fetches. */
preview_url?: string;
status: CoursePlanMediaStatus;
error: string;
cost_cents: number;
created_at: string | null;
}
// ---------------------------------------------------------------------------
// Phase D — Assignments
// ---------------------------------------------------------------------------
export type CoursePlanAssignmentMode = "batch" | "students" | "entities";
export type CoursePlanAssignmentState = "active" | "archived";
export interface CoursePlanAssignment {
id: number;
plan_id: number;
plan_name: string;
mode: CoursePlanAssignmentMode;
batch_id: number | null;
batch_name: string;
student_user_ids: number[];
student_user_names: string[];
entity_ids?: number[];
entity_names?: string[];
student_count: number;
assigned_by_id: number | null;
assigned_by_name: string;
due_date: string | null;
message: string;
state: CoursePlanAssignmentState;
created_at: string | null;
}
export interface CoursePlan {
id: number;
name: string;
entity_id?: number | null;
entity_name?: string;
course_id: number | null;
course_name: string;
cefr_level: string;
@@ -263,22 +101,13 @@ export interface CoursePlan {
resources: CoursePlanResource[];
week_count: number;
material_count: number;
source_count?: number;
media_count?: number;
assignment_count?: number;
created_at: string | null;
weeks?: CoursePlanWeek[];
materials?: CoursePlanMaterial[];
sources?: CoursePlanSource[];
media?: CoursePlanMedia[];
assignments?: CoursePlanAssignment[];
/** Present on the student-list endpoint payload. */
assignment?: CoursePlanAssignment;
}
export interface CoursePlanGenerateBrief {
title: string;
entity_id?: number;
cefr_level?: string;
total_weeks?: number;
contact_hours_per_week?: number;