CognxSafeTrack commited on
Commit ·
a343cb3
1
Parent(s): 7c7162a
feat(admin): integrate LiveFeed moderation component into the dashboard
Browse filesFiles changed (2)
- apps/admin/src/App.tsx+110-103
- apps/admin/src/pages/LiveFeed.tsxAdded+376
123456789101112131415161759 unmodified lines7778798081828384851 unmodified line878889909192939495969798999 unmodified lines1091101111121131141151161171181191201211221231241251261274 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802811 unmodified line2832842852862872882892902912922932942952962972982993003013023033043053063073083092 unmodified lines31231331431531631731831932032132232332432532632732832933033133233333433533633733833934010 unmodified lines3513523533543553563576 unmodified lines3643653663673683693703713723733743753763773783793803 unmodified lines3843853863873883893903913923933943953965 unmodified lines402403404405406407408409import { BrowserRouter as Router, Routes, Route, Link, Navigate, useNavigate, useParams } from 'react-router-dom';import { useEffect, useState, createContext, useContext } from 'react';import { Users, PlayCircle, CheckCircle, Lightbulb, Download, BookOpen, Plus, Edit2, Trash2, ChevronRight, X, Save, BarChart2, DollarSign, ArrowLeft } from 'lucide-react';const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';const SESSION_KEY = 'edtech_admin_key';const AuthContext = createContext<{ apiKey: string | null; login: (k: string) => void; logout: () => void; }>({ apiKey: null, login: () => {}, logout: () => {} });function AuthProvider({ children }: { children: React.ReactNode }) {const [apiKey, setApiKey] = useState<string | null>(() => sessionStorage.getItem(SESSION_KEY));const login = (k: string) => { sessionStorage.setItem(SESSION_KEY, k); setApiKey(k); };const logout = () => { sessionStorage.removeItem(SESSION_KEY); setApiKey(null); };return <AuthContext.Provider value={{ apiKey, login, logout }}>{children}</AuthContext.Provider>;}const useAuth = () => useContext(AuthContext);const ah = (k: string) => ({ 'Authorization': `Bearer ${k}`, 'Content-Type': 'application/json' });function ProtectedRoute({ children }: { children: React.ReactNode }) {const { apiKey } = useAuth();59 unmodified linesconst exportCSV = () => {if (!enrollments.length) return alert('Aucune inscription.');const rows = enrollments.map((e: any) => [e.id, e.user?.phone, e.track?.title, e.status, e.currentDay, e.startedAt]);const csv = [['ID','Phone','Track','Status','Day','Started'].join(','), ...rows.map(r => r.join(','))].join('\n');const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));a.download = `enrollments_${new Date().toISOString().slice(0,10)}.csv`; a.click();};if (loading) return <div className="p-8 text-slate-400">Chargement...</div>;const statCards = [1 unmodified line{ icon: <PlayCircle className="w-6 h-6 text-blue-400" />, label: 'Actifs', value: stats?.activeEnrollments || 0, color: 'text-blue-600' },{ icon: <CheckCircle className="w-6 h-6 text-green-400" />, label: 'Complétés', value: stats?.completedEnrollments || 0, color: 'text-green-600' },{ icon: <Lightbulb className="w-6 h-6 text-purple-400" />, label: 'Parcours', value: stats?.totalTracks || 0, color: 'text-purple-600' },{ icon: <DollarSign className="w-6 h-6 text-emerald-400" />, label: 'Revenus', value: `${(stats?.totalRevenue||0).toLocaleString()} XOF`, color: 'text-emerald-600' },];return (<div className="p-8"><h1 className="text-3xl font-bold mb-8 text-slate-800">Dashboard</h1><div className="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-8">{statCards.map((s,i) => (<div key={i} className="bg-white p-5 rounded-xl shadow-sm border border-slate-100 flex flex-col items-center gap-2">{s.icon}<p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">{s.label}</p><p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>9 unmodified lines</div><table className="w-full text-sm"><thead className="bg-slate-50 text-xs text-slate-500 uppercase"><tr>{['Téléphone','Parcours','Statut','Jour','Date'].map(h=><th key={h} className="px-6 py-3 text-left">{h}</th>)}</tr></thead><tbody>{enrollments.map((e:any)=>(<tr key={e.id} className="border-t border-slate-50 hover:bg-slate-50/50"><td className="px-6 py-4 font-medium text-slate-900">{e.user?.phone||'—'}</td><td className="px-6 py-4">{e.track?.title||'—'}</td><td className="px-6 py-4"><span className={`px-2 py-1 rounded-full text-xs font-medium ${e.status==='ACTIVE'?'bg-blue-100 text-blue-800':e.status==='COMPLETED'?'bg-green-100 text-green-800':'bg-slate-100 text-slate-800'}`}>{e.status}</span></td><td className="px-6 py-4">Jour {e.currentDay}</td><td className="px-6 py-4 text-slate-500">{new Date(e.startedAt).toLocaleDateString('fr-FR')}</td></tr>))}{!enrollments.length&&<tr><td colSpan={5} className="px-6 py-8 text-center text-slate-400">Aucune inscription</td></tr>}</tbody></table></div>4 unmodified linesfunction TrackList() {const { apiKey } = useAuth(); const navigate = useNavigate();const [tracks, setTracks] = useState<any[]>([]); const [loading, setLoading] = useState(true);const load = async () => { const r = await fetch(`${API_URL}/v1/admin/tracks`,{headers:ah(apiKey!)}); setTracks(await r.json()); setLoading(false); };useEffect(()=>{ load(); },[]);const del = async(id:string)=>{ if(!confirm('Supprimer ce parcours ?')) return; await fetch(`${API_URL}/v1/admin/tracks/${id}`,{method:'DELETE',headers:ah(apiKey!)}); load(); };if(loading) return <div className="p-8 text-slate-400">Chargement...</div>;return (<div className="p-8"><div className="flex justify-between items-center mb-6"><h1 className="text-3xl font-bold text-slate-800">Parcours</h1><button onClick={()=>navigate('/content/new')} className="flex items-center gap-2 bg-slate-900 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-slate-700"><Plus className="w-4 h-4"/> Nouveau parcours</button></div><div className="grid gap-4">{tracks.map((t:any)=>(<div key={t.id} className="bg-white rounded-xl border border-slate-100 p-5 flex items-center justify-between shadow-sm hover:shadow-md transition"><div className="flex items-center gap-4"><div className="bg-purple-100 p-3 rounded-xl"><BookOpen className="w-5 h-5 text-purple-600"/></div><div><div className="flex items-center gap-2"><h3 className="font-bold text-slate-800">{t.title}</h3>{t.isPremium&&<span className="bg-amber-100 text-amber-700 text-xs px-2 py-0.5 rounded-full font-medium">Premium</span>}<span className="bg-slate-100 text-slate-600 text-xs px-2 py-0.5 rounded-full">{t.language}</span></div><p className="text-sm text-slate-500 mt-0.5">{t._count?.days||0} jours · {t._count?.enrollments||0} inscrits · {t.duration}j</p></div></div><div className="flex items-center gap-2"><button onClick={()=>navigate(`/content/${t.id}`)} className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg"><Edit2 className="w-4 h-4"/></button><button onClick={()=>navigate(`/content/${t.id}/days`)} className="flex items-center gap-1 text-sm text-slate-600 hover:text-slate-900 px-3 py-2 rounded-lg hover:bg-slate-50">Jours <ChevronRight className="w-4 h-4"/></button><button onClick={()=>del(t.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4"/></button></div></div>))}{!tracks.length&&<div className="text-center py-16 text-slate-400"><BookOpen className="w-12 h-12 mx-auto mb-3 opacity-30"/><p>Aucun parcours. Créez-en un !</p></div>}</div></div>);}function TrackForm() {const { apiKey } = useAuth(); const { id } = useParams<{id:string}>(); const navigate = useNavigate();const isNew = id==='new';const [form, setForm] = useState({title:'',description:'',duration:7,language:'FR',isPremium:false,priceAmount:0,stripePriceId:''});const [saving, setSaving] = useState(false);useEffect(()=>{ if(!isNew) fetch(`${API_URL}/v1/admin/tracks/${id}`,{headers:ah(apiKey!)}).then(r=>r.json()).then(t=>setForm({title:t.title,description:t.description||'',duration:t.duration,language:t.language,isPremium:t.isPremium,priceAmount:t.priceAmount||0,stripePriceId:t.stripePriceId||''})); },[id]);const inp = "w-full border border-slate-200 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-slate-300";const handleSubmit = async(e:React.FormEvent)=>{ e.preventDefault(); setSaving(true);const url = isNew?`${API_URL}/v1/admin/tracks`:`${API_URL}/v1/admin/tracks/${id}`;await fetch(url,{method:isNew?'POST':'PUT',headers:ah(apiKey!),body:JSON.stringify({...form,priceAmount:form.priceAmount||undefined,stripePriceId:form.stripePriceId||undefined})});navigate('/content'); };return (<div className="p-8 max-w-xl"><div className="flex items-center gap-3 mb-6"><button onClick={()=>navigate('/content')} className="p-2 hover:bg-slate-100 rounded-lg"><ArrowLeft className="w-4 h-4"/></button><h1 className="text-2xl font-bold text-slate-800">{isNew?'Nouveau parcours':'Modifier le parcours'}</h1></div><form onSubmit={handleSubmit} className="bg-white rounded-2xl border border-slate-100 p-6 space-y-4 shadow-sm"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Titre *</label><input required className={inp} value={form.title} onChange={e=>setForm(f=>({...f,title:e.target.value}))}/></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Description</label><textarea className={inp} rows={3} value={form.description} onChange={e=>setForm(f=>({...f,description:e.target.value}))}/></div><div className="grid grid-cols-2 gap-4"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Durée (jours)</label><input type="number" min={1} required className={inp} value={form.duration} onChange={e=>setForm(f=>({...f,duration:parseInt(e.target.value)}))}/></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Langue</label><select className={inp} value={form.language} onChange={e=>setForm(f=>({...f,language:e.target.value}))}><option value="FR">Français</option><option value="WOLOF">Wolof</option></select></div></div><label className="flex items-center gap-3 p-3 bg-amber-50 rounded-xl cursor-pointer"><input type="checkbox" checked={form.isPremium} onChange={e=>setForm(f=>({...f,isPremium:e.target.checked}))} className="w-4 h-4"/><span className="text-sm font-medium text-amber-800">Formation Premium (payante)</span></label>{form.isPremium&&<div className="grid grid-cols-2 gap-4"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Prix (XOF)</label><input type="number" className={inp} value={form.priceAmount} onChange={e=>setForm(f=>({...f,priceAmount:parseInt(e.target.value)}))}/></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Stripe Price ID</label><input className={inp} value={form.stripePriceId} onChange={e=>setForm(f=>({...f,stripePriceId:e.target.value}))}/></div></div>}<div className="flex gap-3 pt-2"><button type="button" onClick={()=>navigate('/content')} className="flex-1 border border-slate-200 text-slate-600 py-2.5 rounded-xl text-sm hover:bg-slate-50">Annuler</button><button type="submit" disabled={saving} className="flex-1 bg-slate-900 text-white py-2.5 rounded-xl text-sm font-bold flex items-center justify-center gap-2 hover:bg-slate-700 disabled:opacity-50"><Save className="w-4 h-4"/>{saving?'Enregistrement...':'Enregistrer'}</button></div></form>2 unmodified lines}function TrackDays() {const { apiKey } = useAuth(); const { trackId } = useParams<{trackId:string}>(); const navigate = useNavigate();const [days, setDays] = useState<any[]>([]); const [track, setTrack] = useState<any>(null); const [editing, setEditing] = useState<any>(null); const [saving, setSaving] = useState(false);const load = async()=>{ const[tR,dR]=await Promise.all([fetch(`${API_URL}/v1/admin/tracks/${trackId}`,{headers:ah(apiKey!)}),fetch(`${API_URL}/v1/admin/tracks/${trackId}/days`,{headers:ah(apiKey!)})]); setTrack(await tR.json()); setDays(await dR.json()); };useEffect(()=>{ load(); },[]);const emptyDay = {dayNumber:(days.length||0)+1,title:'',lessonText:'',audioUrl:'',exerciseType:'TEXT',exercisePrompt:'',validationKeyword:''};const saveDay = async(e:React.FormEvent)=>{ e.preventDefault(); setSaving(true);const url = editing.id?`${API_URL}/v1/admin/tracks/${trackId}/days/${editing.id}`:`${API_URL}/v1/admin/tracks/${trackId}/days`;await fetch(url,{method:editing.id?'PUT':'POST',headers:ah(apiKey!),body:JSON.stringify(editing)});setEditing(null); load(); setSaving(false); };const del = async(dayId:string)=>{ if(!confirm('Supprimer ce jour?')) return; await fetch(`${API_URL}/v1/admin/tracks/${trackId}/days/${dayId}`,{method:'DELETE',headers:ah(apiKey!)}); load(); };const inp = "w-full border border-slate-200 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-slate-300";return (<div className="p-8"><div className="flex items-center gap-3 mb-6"><button onClick={()=>navigate('/content')} className="p-2 hover:bg-slate-100 rounded-lg"><ArrowLeft className="w-4 h-4"/></button><div><h1 className="text-2xl font-bold text-slate-800">{track?.title}</h1><p className="text-sm text-slate-500">{days.length} jours configurés</p></div><button onClick={()=>setEditing(emptyDay)} className="ml-auto flex items-center gap-2 bg-slate-900 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-slate-700"><Plus className="w-4 h-4"/> Ajouter un jour</button></div>{editing&&(<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"><div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto"><div className="flex items-center justify-between p-5 border-b"><h2 className="font-bold text-slate-800">{editing.id?`Modifier Jour ${editing.dayNumber}`:'Nouveau jour'}</h2><button onClick={()=>setEditing(null)}><X className="w-5 h-5 text-slate-400"/></button></div><form onSubmit={saveDay} className="p-5 space-y-4"><div className="grid grid-cols-2 gap-3"><div><label className="text-xs font-medium text-slate-600 mb-1 block">Numéro du jour</label><input type="number" min={1} required className={inp} value={editing.dayNumber} onChange={e=>setEditing((d:any)=>({...d,dayNumber:parseInt(e.target.value)}))}/></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Titre</label><input className={inp} value={editing.title||''} onChange={e=>setEditing((d:any)=>({...d,title:e.target.value}))}/></div></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Texte de la leçon</label><textarea className={inp} rows={5} value={editing.lessonText||''} onChange={e=>setEditing((d:any)=>({...d,lessonText:e.target.value}))} placeholder="Contenu pédagogique..."/></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">URL Audio (optionnel)</label><input className={inp} value={editing.audioUrl||''} onChange={e=>setEditing((d:any)=>({...d,audioUrl:e.target.value}))} placeholder="https://..."/></div><div className="grid grid-cols-2 gap-3"><div><label className="text-xs font-medium text-slate-600 mb-1 block">Type exercice</label><select className={inp} value={editing.exerciseType} onChange={e=>setEditing((d:any)=>({...d,exerciseType:e.target.value}))}><option value="TEXT">Texte libre</option><option value="AUDIO">Audio</option><option value="BUTTON">Boutons</option></select></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Mot-clé validation</label><input className={inp} value={editing.validationKeyword||''} onChange={e=>setEditing((d:any)=>({...d,validationKeyword:e.target.value}))}/></div></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Prompt exercice</label><textarea className={inp} rows={2} value={editing.exercisePrompt||''} onChange={e=>setEditing((d:any)=>({...d,exercisePrompt:e.target.value}))} placeholder="Question posée à l'étudiant..."/></div><div className="flex gap-3"><button type="button" onClick={()=>setEditing(null)} className="flex-1 border border-slate-200 text-slate-600 py-2.5 rounded-xl text-sm hover:bg-slate-50">Annuler</button><button type="submit" disabled={saving} className="flex-1 bg-slate-900 text-white py-2.5 rounded-xl text-sm font-bold flex items-center justify-center gap-2 hover:bg-slate-700 disabled:opacity-50"><Save className="w-4 h-4"/>{saving?'Enregistrement...':'Enregistrer'}</button></div></form>1 unmodified line</div>)}<div className="grid gap-3">{days.map((d:any)=>(<div key={d.id} className="bg-white rounded-xl border border-slate-100 p-4 flex items-start justify-between shadow-sm"><div className="flex gap-4"><div className="bg-slate-900 text-white w-9 h-9 rounded-lg flex items-center justify-center text-sm font-bold shrink-0">{d.dayNumber}</div><div><p className="font-medium text-slate-800">{d.title||`Jour ${d.dayNumber}`}</p><p className="text-xs text-slate-500 mt-0.5 line-clamp-1">{d.lessonText?.substring(0,100)||'Pas de texte'}</p><div className="flex gap-2 mt-1.5"><span className="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full">{d.exerciseType}</span>{d.audioUrl&&<span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">🎵 Audio</span>}{d.exercisePrompt&&<span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">🎯 Exercice</span>}</div></div></div><div className="flex gap-1 shrink-0 ml-4"><button onClick={()=>setEditing(d)} className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg"><Edit2 className="w-4 h-4"/></button><button onClick={()=>del(d.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4"/></button></div></div>))}{!days.length&&<div className="text-center py-12 text-slate-400 bg-white rounded-xl border border-dashed border-slate-200"><p>Aucun jour. Ajoutez le contenu pédagogique !</p></div>}</div></div>);2 unmodified linesfunction UserList() {const { apiKey } = useAuth();const [users, setUsers] = useState<any[]>([]); const [total, setTotal] = useState(0); const [loading, setLoading] = useState(true);useEffect(()=>{ fetch(`${API_URL}/v1/admin/users`,{headers:ah(apiKey!)}).then(r=>r.json()).then(d=>{ setUsers(d.users||d); setTotal(d.total||0); setLoading(false); }); },[]);if(loading) return <div className="p-8 text-slate-400">Chargement...</div>;return (<div className="p-8"><h1 className="text-3xl font-bold mb-6 text-slate-800">Utilisateurs <span className="text-lg font-normal text-slate-400">({total})</span></h1><div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden"><table className="w-full text-sm"><thead className="bg-slate-50 text-xs text-slate-500 uppercase"><tr>{['Téléphone','Nom','Langue','Secteur','Inscrip.','Réponses','Date'].map(h=><th key={h} className="px-5 py-3 text-left">{h}</th>)}</tr></thead><tbody>{users.map((u:any)=>(<tr key={u.id} className="border-t border-slate-50 hover:bg-slate-50/50"><td className="px-5 py-3 font-medium">{u.phone}</td><td className="px-5 py-3 text-slate-600">{u.name||'—'}</td><td className="px-5 py-3"><span className="bg-blue-100 text-blue-700 text-xs px-2 py-0.5 rounded-full">{u.language}</span></td><td className="px-5 py-3 text-slate-500 text-xs">{u.activity||'—'}</td><td className="px-5 py-3 text-center">{u._count?.enrollments||0}</td><td className="px-5 py-3 text-center">{u._count?.responses||0}</td><td className="px-5 py-3 text-slate-400 text-xs">{new Date(u.createdAt).toLocaleDateString('fr-FR')}</td></tr>))}{!users.length&&<tr><td colSpan={7} className="px-5 py-8 text-center text-slate-400">Aucun utilisateur</td></tr>}</tbody></table></div>10 unmodified lines<div><p className="font-medium text-slate-800">API URL</p><p className="text-sm text-slate-500 font-mono">{API_URL}</p></div></div><p className="text-sm font-medium text-slate-600">Variables Railway requises :</p>{['WHATSAPP_VERIFY_TOKEN','WHATSAPP_APP_SECRET','WHATSAPP_ACCESS_TOKEN','OPENAI_API_KEY','DATABASE_URL','REDIS_URL','API_URL','ADMIN_API_KEY'].map(v=>(<div key={v} className="flex items-center gap-3 p-3 border border-slate-100 rounded-xl"><span className="font-mono text-xs text-slate-700">{v}</span></div>6 unmodified linesfunction AppShell() {const { logout } = useAuth();const navItems = [{ to:'/', label:'Dashboard', icon:<BarChart2 className="w-4 h-4"/> },{ to:'/content', label:'Parcours', icon:<BookOpen className="w-4 h-4"/> },{ to:'/users', label:'Utilisateurs', icon:<Users className="w-4 h-4"/> },{ to:'/settings', label:'Paramètres', icon:<Lightbulb className="w-4 h-4"/> },];return (<div className="min-h-screen bg-gray-50 flex"><aside className="w-56 bg-slate-900 text-white p-5 flex flex-col shrink-0"><div className="text-lg font-bold mb-8 flex items-center gap-2"><span className="text-2xl">🎓</span>EdTech Admin</div><nav className="space-y-1 flex-1">{navItems.map(n=>(<Link key={n.to} to={n.to} className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:text-white hover:bg-slate-800 transition">{n.icon}{n.label}</Link>3 unmodified lines</aside><main className="flex-1 overflow-auto"><Routes><Route path="/" element={<Dashboard/>}/><Route path="/content" element={<TrackList/>}/><Route path="/content/new" element={<TrackForm/>}/><Route path="/content/:id" element={<TrackForm/>}/><Route path="/content/:trackId/days" element={<TrackDays/>}/><Route path="/users" element={<UserList/>}/><Route path="/settings" element={<Settings/>}/></Routes></main></div>5 unmodified lines<AuthProvider><Router><Routes><Route path="/login" element={<LoginPage/>}/><Route path="/*" element={<ProtectedRoute><AppShell/></ProtectedRoute>}/></Routes></Router></AuthProvider>12345678910111213141516171859 unmodified lines7879808182838485861 unmodified line8889909192939495969798991009 unmodified lines1101111121131141151161171181191201211221231241251261271284 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852861 unmodified line2882892902912922932942952962972982993003013023033043053063073083093103113123133142 unmodified lines31731831932032132232332432532632732832933033133233333433533633733833934034134234334434510 unmodified lines3563573583593603613626 unmodified lines3693703713723733743753763773783793803813823833843853863 unmodified lines3903913923933943953963973983994004014024035 unmodified lines409410411412413414415416import { BrowserRouter as Router, Routes, Route, Link, Navigate, useNavigate, useParams } from 'react-router-dom';import { useEffect, useState, createContext, useContext } from 'react';import { Users, PlayCircle, CheckCircle, Lightbulb, Download, BookOpen, Plus, Edit2, Trash2, ChevronRight, X, Save, BarChart2, DollarSign, ArrowLeft, Mic } from 'lucide-react';import LiveFeed from './pages/LiveFeed';const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';const SESSION_KEY = 'edtech_admin_key';export const AuthContext = createContext<{ apiKey: string | null; login: (k: string) => void; logout: () => void; }>({ apiKey: null, login: () => { }, logout: () => { } });function AuthProvider({ children }: { children: React.ReactNode }) {const [apiKey, setApiKey] = useState<string | null>(() => sessionStorage.getItem(SESSION_KEY));const login = (k: string) => { sessionStorage.setItem(SESSION_KEY, k); setApiKey(k); };const logout = () => { sessionStorage.removeItem(SESSION_KEY); setApiKey(null); };return <AuthContext.Provider value={{ apiKey, login, logout }}>{children}</AuthContext.Provider>;}export const useAuth = () => useContext(AuthContext);const ah = (k: string) => ({ 'Authorization': `Bearer ${k}`, 'Content-Type': 'application/json' });function ProtectedRoute({ children }: { children: React.ReactNode }) {const { apiKey } = useAuth();59 unmodified linesconst exportCSV = () => {if (!enrollments.length) return alert('Aucune inscription.');const rows = enrollments.map((e: any) => [e.id, e.user?.phone, e.track?.title, e.status, e.currentDay, e.startedAt]);const csv = [['ID', 'Phone', 'Track', 'Status', 'Day', 'Started'].join(','), ...rows.map(r => r.join(','))].join('\n');const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));a.download = `enrollments_${new Date().toISOString().slice(0, 10)}.csv`; a.click();};if (loading) return <div className="p-8 text-slate-400">Chargement...</div>;const statCards = [1 unmodified line{ icon: <PlayCircle className="w-6 h-6 text-blue-400" />, label: 'Actifs', value: stats?.activeEnrollments || 0, color: 'text-blue-600' },{ icon: <CheckCircle className="w-6 h-6 text-green-400" />, label: 'Complétés', value: stats?.completedEnrollments || 0, color: 'text-green-600' },{ icon: <Lightbulb className="w-6 h-6 text-purple-400" />, label: 'Parcours', value: stats?.totalTracks || 0, color: 'text-purple-600' },{ icon: <DollarSign className="w-6 h-6 text-emerald-400" />, label: 'Revenus', value: `${(stats?.totalRevenue || 0).toLocaleString()} XOF`, color: 'text-emerald-600' },];return (<div className="p-8"><h1 className="text-3xl font-bold mb-8 text-slate-800">Dashboard</h1><div className="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-8">{statCards.map((s, i) => (<div key={i} className="bg-white p-5 rounded-xl shadow-sm border border-slate-100 flex flex-col items-center gap-2">{s.icon}<p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">{s.label}</p><p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>9 unmodified lines</div><table className="w-full text-sm"><thead className="bg-slate-50 text-xs text-slate-500 uppercase"><tr>{['Téléphone', 'Parcours', 'Statut', 'Jour', 'Date'].map(h => <th key={h} className="px-6 py-3 text-left">{h}</th>)}</tr></thead><tbody>{enrollments.map((e: any) => (<tr key={e.id} className="border-t border-slate-50 hover:bg-slate-50/50"><td className="px-6 py-4 font-medium text-slate-900">{e.user?.phone || '—'}</td><td className="px-6 py-4">{e.track?.title || '—'}</td><td className="px-6 py-4"><span className={`px-2 py-1 rounded-full text-xs font-medium ${e.status === 'ACTIVE' ? 'bg-blue-100 text-blue-800' : e.status === 'COMPLETED' ? 'bg-green-100 text-green-800' : 'bg-slate-100 text-slate-800'}`}>{e.status}</span></td><td className="px-6 py-4">Jour {e.currentDay}</td><td className="px-6 py-4 text-slate-500">{new Date(e.startedAt).toLocaleDateString('fr-FR')}</td></tr>))}{!enrollments.length && <tr><td colSpan={5} className="px-6 py-8 text-center text-slate-400">Aucune inscription</td></tr>}</tbody></table></div>4 unmodified linesfunction TrackList() {const { apiKey } = useAuth(); const navigate = useNavigate();const [tracks, setTracks] = useState<any[]>([]); const [loading, setLoading] = useState(true);const load = async () => { const r = await fetch(`${API_URL}/v1/admin/tracks`, { headers: ah(apiKey!) }); setTracks(await r.json()); setLoading(false); };useEffect(() => { load(); }, []);const del = async (id: string) => { if (!confirm('Supprimer ce parcours ?')) return; await fetch(`${API_URL}/v1/admin/tracks/${id}`, { method: 'DELETE', headers: ah(apiKey!) }); load(); };if (loading) return <div className="p-8 text-slate-400">Chargement...</div>;return (<div className="p-8"><div className="flex justify-between items-center mb-6"><h1 className="text-3xl font-bold text-slate-800">Parcours</h1><button onClick={() => navigate('/content/new')} className="flex items-center gap-2 bg-slate-900 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-slate-700"><Plus className="w-4 h-4" /> Nouveau parcours</button></div><div className="grid gap-4">{tracks.map((t: any) => (<div key={t.id} className="bg-white rounded-xl border border-slate-100 p-5 flex items-center justify-between shadow-sm hover:shadow-md transition"><div className="flex items-center gap-4"><div className="bg-purple-100 p-3 rounded-xl"><BookOpen className="w-5 h-5 text-purple-600" /></div><div><div className="flex items-center gap-2"><h3 className="font-bold text-slate-800">{t.title}</h3>{t.isPremium && <span className="bg-amber-100 text-amber-700 text-xs px-2 py-0.5 rounded-full font-medium">Premium</span>}<span className="bg-slate-100 text-slate-600 text-xs px-2 py-0.5 rounded-full">{t.language}</span></div><p className="text-sm text-slate-500 mt-0.5">{t._count?.days || 0} jours · {t._count?.enrollments || 0} inscrits · {t.duration}j</p></div></div><div className="flex items-center gap-2"><button onClick={() => navigate(`/content/${t.id}`)} className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg"><Edit2 className="w-4 h-4" /></button><button onClick={() => navigate(`/content/${t.id}/days`)} className="flex items-center gap-1 text-sm text-slate-600 hover:text-slate-900 px-3 py-2 rounded-lg hover:bg-slate-50">Jours <ChevronRight className="w-4 h-4" /></button><button onClick={() => del(t.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button></div></div>))}{!tracks.length && <div className="text-center py-16 text-slate-400"><BookOpen className="w-12 h-12 mx-auto mb-3 opacity-30" /><p>Aucun parcours. Créez-en un !</p></div>}</div></div>);}function TrackForm() {const { apiKey } = useAuth(); const { id } = useParams<{ id: string }>(); const navigate = useNavigate();const isNew = id === 'new';const [form, setForm] = useState({ title: '', description: '', duration: 7, language: 'FR', isPremium: false, priceAmount: 0, stripePriceId: '' });const [saving, setSaving] = useState(false);useEffect(() => { if (!isNew) fetch(`${API_URL}/v1/admin/tracks/${id}`, { headers: ah(apiKey!) }).then(r => r.json()).then(t => setForm({ title: t.title, description: t.description || '', duration: t.duration, language: t.language, isPremium: t.isPremium, priceAmount: t.priceAmount || 0, stripePriceId: t.stripePriceId || '' })); }, [id]);const inp = "w-full border border-slate-200 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-slate-300";const handleSubmit = async (e: React.FormEvent) => {e.preventDefault(); setSaving(true);const url = isNew ? `${API_URL}/v1/admin/tracks` : `${API_URL}/v1/admin/tracks/${id}`;await fetch(url, { method: isNew ? 'POST' : 'PUT', headers: ah(apiKey!), body: JSON.stringify({ ...form, priceAmount: form.priceAmount || undefined, stripePriceId: form.stripePriceId || undefined }) });navigate('/content');};return (<div className="p-8 max-w-xl"><div className="flex items-center gap-3 mb-6"><button onClick={() => navigate('/content')} className="p-2 hover:bg-slate-100 rounded-lg"><ArrowLeft className="w-4 h-4" /></button><h1 className="text-2xl font-bold text-slate-800">{isNew ? 'Nouveau parcours' : 'Modifier le parcours'}</h1></div><form onSubmit={handleSubmit} className="bg-white rounded-2xl border border-slate-100 p-6 space-y-4 shadow-sm"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Titre *</label><input required className={inp} value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} /></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Description</label><textarea className={inp} rows={3} value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} /></div><div className="grid grid-cols-2 gap-4"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Durée (jours)</label><input type="number" min={1} required className={inp} value={form.duration} onChange={e => setForm(f => ({ ...f, duration: parseInt(e.target.value) }))} /></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Langue</label><select className={inp} value={form.language} onChange={e => setForm(f => ({ ...f, language: e.target.value }))}><option value="FR">Français</option><option value="WOLOF">Wolof</option></select></div></div><label className="flex items-center gap-3 p-3 bg-amber-50 rounded-xl cursor-pointer"><input type="checkbox" checked={form.isPremium} onChange={e => setForm(f => ({ ...f, isPremium: e.target.checked }))} className="w-4 h-4" /><span className="text-sm font-medium text-amber-800">Formation Premium (payante)</span></label>{form.isPremium && <div className="grid grid-cols-2 gap-4"><div><label className="text-sm font-medium text-slate-700 mb-1 block">Prix (XOF)</label><input type="number" className={inp} value={form.priceAmount} onChange={e => setForm(f => ({ ...f, priceAmount: parseInt(e.target.value) }))} /></div><div><label className="text-sm font-medium text-slate-700 mb-1 block">Stripe Price ID</label><input className={inp} value={form.stripePriceId} onChange={e => setForm(f => ({ ...f, stripePriceId: e.target.value }))} /></div></div>}<div className="flex gap-3 pt-2"><button type="button" onClick={() => navigate('/content')} className="flex-1 border border-slate-200 text-slate-600 py-2.5 rounded-xl text-sm hover:bg-slate-50">Annuler</button><button type="submit" disabled={saving} className="flex-1 bg-slate-900 text-white py-2.5 rounded-xl text-sm font-bold flex items-center justify-center gap-2 hover:bg-slate-700 disabled:opacity-50"><Save className="w-4 h-4" />{saving ? 'Enregistrement...' : 'Enregistrer'}</button></div></form>2 unmodified lines}function TrackDays() {const { apiKey } = useAuth(); const { trackId } = useParams<{ trackId: string }>(); const navigate = useNavigate();const [days, setDays] = useState<any[]>([]); const [track, setTrack] = useState<any>(null); const [editing, setEditing] = useState<any>(null); const [saving, setSaving] = useState(false);const load = async () => { const [tR, dR] = await Promise.all([fetch(`${API_URL}/v1/admin/tracks/${trackId}`, { headers: ah(apiKey!) }), fetch(`${API_URL}/v1/admin/tracks/${trackId}/days`, { headers: ah(apiKey!) })]); setTrack(await tR.json()); setDays(await dR.json()); };useEffect(() => { load(); }, []);const emptyDay = { dayNumber: (days.length || 0) + 1, title: '', lessonText: '', audioUrl: '', exerciseType: 'TEXT', exercisePrompt: '', validationKeyword: '' };const saveDay = async (e: React.FormEvent) => {e.preventDefault(); setSaving(true);const url = editing.id ? `${API_URL}/v1/admin/tracks/${trackId}/days/${editing.id}` : `${API_URL}/v1/admin/tracks/${trackId}/days`;await fetch(url, { method: editing.id ? 'PUT' : 'POST', headers: ah(apiKey!), body: JSON.stringify(editing) });setEditing(null); load(); setSaving(false);};const del = async (dayId: string) => { if (!confirm('Supprimer ce jour?')) return; await fetch(`${API_URL}/v1/admin/tracks/${trackId}/days/${dayId}`, { method: 'DELETE', headers: ah(apiKey!) }); load(); };const inp = "w-full border border-slate-200 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-slate-300";return (<div className="p-8"><div className="flex items-center gap-3 mb-6"><button onClick={() => navigate('/content')} className="p-2 hover:bg-slate-100 rounded-lg"><ArrowLeft className="w-4 h-4" /></button><div><h1 className="text-2xl font-bold text-slate-800">{track?.title}</h1><p className="text-sm text-slate-500">{days.length} jours configurés</p></div><button onClick={() => setEditing(emptyDay)} className="ml-auto flex items-center gap-2 bg-slate-900 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-slate-700"><Plus className="w-4 h-4" /> Ajouter un jour</button></div>{editing && (<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"><div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto"><div className="flex items-center justify-between p-5 border-b"><h2 className="font-bold text-slate-800">{editing.id ? `Modifier Jour ${editing.dayNumber}` : 'Nouveau jour'}</h2><button onClick={() => setEditing(null)}><X className="w-5 h-5 text-slate-400" /></button></div><form onSubmit={saveDay} className="p-5 space-y-4"><div className="grid grid-cols-2 gap-3"><div><label className="text-xs font-medium text-slate-600 mb-1 block">Numéro du jour</label><input type="number" min={1} required className={inp} value={editing.dayNumber} onChange={e => setEditing((d: any) => ({ ...d, dayNumber: parseInt(e.target.value) }))} /></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Titre</label><input className={inp} value={editing.title || ''} onChange={e => setEditing((d: any) => ({ ...d, title: e.target.value }))} /></div></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Texte de la leçon</label><textarea className={inp} rows={5} value={editing.lessonText || ''} onChange={e => setEditing((d: any) => ({ ...d, lessonText: e.target.value }))} placeholder="Contenu pédagogique..." /></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">URL Audio (optionnel)</label><input className={inp} value={editing.audioUrl || ''} onChange={e => setEditing((d: any) => ({ ...d, audioUrl: e.target.value }))} placeholder="https://..." /></div><div className="grid grid-cols-2 gap-3"><div><label className="text-xs font-medium text-slate-600 mb-1 block">Type exercice</label><select className={inp} value={editing.exerciseType} onChange={e => setEditing((d: any) => ({ ...d, exerciseType: e.target.value }))}><option value="TEXT">Texte libre</option><option value="AUDIO">Audio</option><option value="BUTTON">Boutons</option></select></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Mot-clé validation</label><input className={inp} value={editing.validationKeyword || ''} onChange={e => setEditing((d: any) => ({ ...d, validationKeyword: e.target.value }))} /></div></div><div><label className="text-xs font-medium text-slate-600 mb-1 block">Prompt exercice</label><textarea className={inp} rows={2} value={editing.exercisePrompt || ''} onChange={e => setEditing((d: any) => ({ ...d, exercisePrompt: e.target.value }))} placeholder="Question posée à l'étudiant..." /></div><div className="flex gap-3"><button type="button" onClick={() => setEditing(null)} className="flex-1 border border-slate-200 text-slate-600 py-2.5 rounded-xl text-sm hover:bg-slate-50">Annuler</button><button type="submit" disabled={saving} className="flex-1 bg-slate-900 text-white py-2.5 rounded-xl text-sm font-bold flex items-center justify-center gap-2 hover:bg-slate-700 disabled:opacity-50"><Save className="w-4 h-4" />{saving ? 'Enregistrement...' : 'Enregistrer'}</button></div></form>1 unmodified line</div>)}<div className="grid gap-3">{days.map((d: any) => (<div key={d.id} className="bg-white rounded-xl border border-slate-100 p-4 flex items-start justify-between shadow-sm"><div className="flex gap-4"><div className="bg-slate-900 text-white w-9 h-9 rounded-lg flex items-center justify-center text-sm font-bold shrink-0">{d.dayNumber}</div><div><p className="font-medium text-slate-800">{d.title || `Jour ${d.dayNumber}`}</p><p className="text-xs text-slate-500 mt-0.5 line-clamp-1">{d.lessonText?.substring(0, 100) || 'Pas de texte'}</p><div className="flex gap-2 mt-1.5"><span className="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full">{d.exerciseType}</span>{d.audioUrl && <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">🎵 Audio</span>}{d.exercisePrompt && <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">🎯 Exercice</span>}</div></div></div><div className="flex gap-1 shrink-0 ml-4"><button onClick={() => setEditing(d)} className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg"><Edit2 className="w-4 h-4" /></button><button onClick={() => del(d.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button></div></div>))}{!days.length && <div className="text-center py-12 text-slate-400 bg-white rounded-xl border border-dashed border-slate-200"><p>Aucun jour. Ajoutez le contenu pédagogique !</p></div>}</div></div>);2 unmodified linesfunction UserList() {const { apiKey } = useAuth();const [users, setUsers] = useState<any[]>([]); const [total, setTotal] = useState(0); const [loading, setLoading] = useState(true);useEffect(() => { fetch(`${API_URL}/v1/admin/users`, { headers: ah(apiKey!) }).then(r => r.json()).then(d => { setUsers(d.users || d); setTotal(d.total || 0); setLoading(false); }); }, []);if (loading) return <div className="p-8 text-slate-400">Chargement...</div>;return (<div className="p-8"><h1 className="text-3xl font-bold mb-6 text-slate-800">Utilisateurs <span className="text-lg font-normal text-slate-400">({total})</span></h1><div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden"><table className="w-full text-sm"><thead className="bg-slate-50 text-xs text-slate-500 uppercase"><tr>{['Téléphone', 'Nom', 'Langue', 'Secteur', 'Inscrip.', 'Réponses', 'Date'].map(h => <th key={h} className="px-5 py-3 text-left">{h}</th>)}</tr></thead><tbody>{users.map((u: any) => (<tr key={u.id} className="border-t border-slate-50 hover:bg-slate-50/50"><td className="px-5 py-3 font-medium">{u.phone}</td><td className="px-5 py-3 text-slate-600">{u.name || '—'}</td><td className="px-5 py-3"><span className="bg-blue-100 text-blue-700 text-xs px-2 py-0.5 rounded-full">{u.language}</span></td><td className="px-5 py-3 text-slate-500 text-xs">{u.activity || '—'}</td><td className="px-5 py-3 text-center">{u._count?.enrollments || 0}</td><td className="px-5 py-3 text-center">{u._count?.responses || 0}</td><td className="px-5 py-3 text-slate-400 text-xs">{new Date(u.createdAt).toLocaleDateString('fr-FR')}</td></tr>))}{!users.length && <tr><td colSpan={7} className="px-5 py-8 text-center text-slate-400">Aucun utilisateur</td></tr>}</tbody></table></div>10 unmodified lines<div><p className="font-medium text-slate-800">API URL</p><p className="text-sm text-slate-500 font-mono">{API_URL}</p></div></div><p className="text-sm font-medium text-slate-600">Variables Railway requises :</p>{['WHATSAPP_VERIFY_TOKEN', 'WHATSAPP_APP_SECRET', 'WHATSAPP_ACCESS_TOKEN', 'OPENAI_API_KEY', 'DATABASE_URL', 'REDIS_URL', 'API_URL', 'ADMIN_API_KEY'].map(v => (<div key={v} className="flex items-center gap-3 p-3 border border-slate-100 rounded-xl"><span className="font-mono text-xs text-slate-700">{v}</span></div>6 unmodified linesfunction AppShell() {const { logout } = useAuth();const navItems = [{ to: '/', label: 'Dashboard', icon: <BarChart2 className="w-4 h-4" /> },{ to: '/content', label: 'Parcours', icon: <BookOpen className="w-4 h-4" /> },{ to: '/live-feed', label: 'Modération', icon: <Mic className="w-4 h-4 text-emerald-500" /> },{ to: '/users', label: 'Utilisateurs', icon: <Users className="w-4 h-4" /> },{ to: '/settings', label: 'Paramètres', icon: <Lightbulb className="w-4 h-4" /> },];return (<div className="min-h-screen bg-gray-50 flex"><aside className="w-56 bg-slate-900 text-white p-5 flex flex-col shrink-0"><div className="text-lg font-bold mb-8 flex items-center gap-2"><span className="text-2xl">🎓</span>EdTech Admin</div><nav className="space-y-1 flex-1">{navItems.map(n => (<Link key={n.to} to={n.to} className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:text-white hover:bg-slate-800 transition">{n.icon}{n.label}</Link>3 unmodified lines</aside><main className="flex-1 overflow-auto"><Routes><Route path="/" element={<Dashboard />} /><Route path="/content" element={<TrackList />} /><Route path="/content/new" element={<TrackForm />} /><Route path="/content/:id" element={<TrackForm />} /><Route path="/content/:trackId/days" element={<TrackDays />} /><Route path="/live-feed" element={<LiveFeed />} /><Route path="/users" element={<UserList />} /><Route path="/settings" element={<Settings />} /></Routes></main></div>5 unmodified lines<AuthProvider><Router><Routes><Route path="/login" element={<LoginPage />} /><Route path="/*" element={<ProtectedRoute><AppShell /></ProtectedRoute>} /></Routes></Router></AuthProvider>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import React, { useState, useEffect, useRef } from 'react';import { Play, Square, Mic, Send, AlertCircle, CheckCircle2, Loader2, User, Briefcase } from 'lucide-react';import { useAuth } from '../App';
interface PendingReview { id: string; userId: string; trackId: string; user: { id: string; name: string | null; phone: string; activity: string | null; language: string; }; track: { id: string; title: string; }; audioUrl: string | null; dayNumber: number;}
export default function LiveFeed() { const [reviews, setReviews] = useState<PendingReview[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [successMsg, setSuccessMsg] = useState<string | null>(null);
const { apiKey } = useAuth(); // MOCK ADMIN ID (Replace with actual auth context) const ADMIN_ID = "admin_01";
// Gestion propre de l'URL de l'API (Support pour Vite, Next.js ou relative) const getApiUrl = (endpoint: string) => { const rawBaseUrl = import.meta.env?.VITE_API_URL || 'http://localhost:3001'; const baseUrl = rawBaseUrl.replace(/\/$/, ''); return `${baseUrl}/v1/admin${endpoint}`; };
const fetchLiveFeed = async () => { try { const res = await fetch(getApiUrl('/live-feed'), { headers: { 'Authorization': `Bearer ${apiKey}` } }); if (!res.ok) throw new Error('Erreur réseau'); const data = await res.json(); setReviews(data); } catch (err: any) { setError(err.message); } finally { setLoading(false); } };
useEffect(() => { fetchLiveFeed(); // Polling every 30 seconds const interval = setInterval(fetchLiveFeed, 30000); return () => clearInterval(interval); }, []);
const handleOverrideSuccess = (userId: string, isSkip: boolean = false) => { setReviews((prev: PendingReview[]) => prev.filter((r: PendingReview) => r.userId !== userId)); if (!isSkip) { setSuccessMsg("Intervention vocale envoyée avec succès !"); setTimeout(() => setSuccessMsg(null), 3000); } };
if (loading) { return ( <div className="flex items-center justify-center p-12"> <Loader2 className="w-8 h-8 animate-spin text-emerald-600" /> </div> ); }
return ( <div className="p-8 max-w-5xl mx-auto"> <div className="flex items-center justify-between mb-8"> <div> <h1 className="text-3xl font-bold tracking-tight text-slate-900">Live Feed Modération</h1> <p className="text-slate-500 mt-2">Étudiants Wolof en attente d'intervention manuelle.</p> </div> <div className="bg-emerald-50 text-emerald-700 px-4 py-2 rounded-full font-medium flex items-center gap-2"> <AlertCircle className="w-5 h-5" /> {reviews.length} En attente </div> </div>
{error && ( <div className="bg-red-50 text-red-600 p-4 rounded-lg mb-8 flex items-center gap-2"> <AlertCircle className="w-5 h-5" /> <p>Erreur lors du chargement: {error}</p> </div> )}
{successMsg && ( <div className="bg-emerald-50 text-emerald-700 p-4 rounded-lg mb-8 flex items-center gap-2 transition-all"> <CheckCircle2 className="w-5 h-5" /> <p>{successMsg}</p> </div> )}
<div className="grid gap-6"> {reviews.length === 0 ? ( <div className="text-center py-24 bg-slate-50 rounded-2xl border border-dashed border-slate-200"> <CheckCircle2 className="w-12 h-12 text-slate-300 mx-auto mb-4" /> <p className="text-slate-500 text-lg">Aucune intervention requise. Excellent travail !</p> </div> ) : ( reviews.map(review => ( <ModerationCard key={review.id} review={review} adminId={ADMIN_ID} onSuccess={() => handleOverrideSuccess(review.userId, false)} onSkip={() => handleOverrideSuccess(review.userId, true)} // Temporarily hide it the same way getApiUrl={getApiUrl} apiKey={apiKey || ''} /> )) )} </div> </div> );}
// ----------------------------------------------------------------------// MODERATION CARD COMPONENT// ----------------------------------------------------------------------
function ModerationCard({ review, adminId, onSuccess, onSkip, getApiUrl, apiKey }: { key?: string | number, review: PendingReview, adminId: string, onSuccess: () => void, onSkip: () => void, getApiUrl: (path: string) => string, apiKey: string }) { const [transcription, setTranscription] = useState(''); const [audioBlob, setAudioBlob] = useState<Blob | null>(null); const [isSubmitting, setIsSubmitting] = useState(false); const audioRef = useRef<HTMLAudioElement>(null); const [playbackRate, setPlaybackRate] = useState(1);
const changeSpeed = () => { const nextRates = { 1: 1.5, 1.5: 2, 2: 1 } as Record<number, number>; const newRate = nextRates[playbackRate] || 1; setPlaybackRate(newRate); if (audioRef.current) { audioRef.current.playbackRate = newRate; } };
const handleSubmit = async () => { if (!transcription || !audioBlob) { alert("Veuillez remplir la transcription ET enregistrer une réponse audio."); return; }
setIsSubmitting(true); let overrideAudioUrl = "";
try { // 1. Upload the AudioBlob to S3/CloudFlare via an upload route const formData = new FormData(); formData.append("file", audioBlob, `override-${review.userId}.webm`);
const uploadRes = await fetch(getApiUrl('/upload'), { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}` }, body: formData });
if (!uploadRes.ok) throw new Error("Erreur lors de l'upload audio"); const uploadData = await uploadRes.json(); overrideAudioUrl = uploadData.url;
// 2. Submit the Override Feedback const feedbackRes = await fetch(getApiUrl('/override-feedback'), { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ userId: review.userId, trackId: review.trackId, transcription: transcription, overrideAudioUrl: overrideAudioUrl, adminId: adminId }) });
if (!feedbackRes.ok) throw new Error("Erreur lors de la validation"); onSuccess();
} catch (err: any) { alert(err.message); } finally { setIsSubmitting(false); } };
return ( <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6 flex flex-col gap-6">
{/* Header: User Info */} <div className="flex items-start justify-between"> <div> <div className="flex items-center gap-3"> <div className="w-10 h-10 bg-indigo-50 rounded-full flex items-center justify-center"> <User className="w-5 h-5 text-indigo-600" /> </div> <div> <h3 className="font-semibold text-slate-900">{review.user.name || review.user.phone}</h3> <p className="text-sm text-slate-500">Jour {review.dayNumber} • {review.track.title}</p> </div> </div> </div> <div className="flex items-center gap-2 bg-slate-50 px-3 py-1.5 rounded-md border border-slate-100"> <Briefcase className="w-4 h-4 text-slate-400" /> <span className="text-sm font-medium text-slate-700">{review.user.activity || "Activité inconnue"}</span> </div> </div>
{/* Body: Audio & Transcription */} <div className="grid md:grid-cols-2 gap-6">
{/* Left Column: Écoute */} <div className="bg-slate-50 p-5 rounded-xl border border-slate-100"> <h4 className="text-sm font-semibold text-slate-700 mb-3 uppercase tracking-wider flex justify-between items-center"> Audio Étudiant (WOLOF) {review.audioUrl && ( <button onClick={changeSpeed} className="text-xs bg-indigo-100 text-indigo-700 px-2 py-1 rounded-md font-medium hover:bg-indigo-200 transition-colors"> Vitesse: {playbackRate}x </button> )} </h4> {review.audioUrl ? ( <audio ref={audioRef} controls src={review.audioUrl} className="w-full h-10" /> ) : ( <p className="text-sm text-slate-400 italic">Aucun fichier audio trouvé.</p> )} </div>
{/* Right Column: Saisie manuelle */} <div> <label className="text-sm font-semibold text-slate-700 mb-2 block uppercase tracking-wider"> Transcription Française <span className="text-red-500">*</span> </label> <textarea className="w-full text-sm p-3 rounded-lg border border-slate-200 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-shadow resize-none h-24" placeholder="Écrivez ce que l'étudiant a dit en le traduisant correctement en français..." value={transcription} onChange={(e: any) => setTranscription(e.target.value)} /> </div> </div>
<hr className="border-slate-100" />
{/* Footer: Admin Voice Overdrive & Action */} <div className="flex items-end justify-between gap-4"> <div className="flex-1"> <label className="text-sm font-semibold text-slate-700 mb-2 block uppercase tracking-wider"> Votre Réponse Audio (WOLOF) <span className="text-red-500">*</span> </label> <AudioRecorder onRecordComplete={setAudioBlob} /> </div>
<div className="flex gap-2"> <button onClick={onSkip} type="button" className="bg-slate-100 hover:bg-slate-200 text-slate-600 px-6 py-3 rounded-xl font-medium shadow-sm transition-colors flex items-center justify-center h-[52px]" > Passer </button> <button onClick={handleSubmit} disabled={isSubmitting || !transcription || !audioBlob} className="bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-300 disabled:cursor-not-allowed text-white px-6 py-3 rounded-xl font-medium shadow-sm transition-colors flex items-center gap-2 h-[52px]" > {isSubmitting ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />} Envoyer Overdrive </button> </div> </div>
</div> );}
// ----------------------------------------------------------------------// AUDIO RECORDER COMPONENT (Web MediaRecorder API)// ----------------------------------------------------------------------
function AudioRecorder({ onRecordComplete }: { onRecordComplete: (blob: Blob | null) => void }) { const [isRecording, setIsRecording] = useState(false); const [audioUrl, setAudioUrl] = useState<string | null>(null);
const mediaRecorder = useRef<MediaRecorder | null>(null); const audioChunks = useRef<BlobPart[]>([]);
const startRecording = async () => { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); mediaRecorder.current = new MediaRecorder(stream); audioChunks.current = [];
mediaRecorder.current.ondataavailable = (event: any) => { audioChunks.current.push(event.data); };
mediaRecorder.current.onstop = () => { const audioBlob = new Blob(audioChunks.current, { type: 'audio/webm' }); const url = URL.createObjectURL(audioBlob); setAudioUrl(url); onRecordComplete(audioBlob); };
mediaRecorder.current.start(); setIsRecording(true); setAudioUrl(null); onRecordComplete(null); } catch (err) { alert("Accès au microphone refusé."); } };
const stopRecording = () => { if (mediaRecorder.current && isRecording) { mediaRecorder.current.stop(); setIsRecording(false); // Stop all tracks to release mic mediaRecorder.current.stream.getTracks().forEach((track: any) => track.stop()); } };
const clearRecording = () => { setAudioUrl(null); onRecordComplete(null); };
return ( <div className="flex items-center gap-3"> {isRecording ? ( <button onClick={stopRecording} className="flex items-center justify-center gap-2 bg-red-100 text-red-600 px-4 h-10 rounded-lg font-medium animate-pulse" > <Square className="w-4 h-4 fill-current" /> Arrêter l'enregistrement </button> ) : ( <button onClick={startRecording} className="flex items-center justify-center gap-2 bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 h-10 rounded-lg font-medium transition-colors" > <Mic className="w-4 h-4" /> Commencer l'enregistrement </button> )}
{audioUrl && !isRecording && ( <div className="flex items-center gap-2 flex-1"> <audio src={audioUrl} controls className="h-10 w-full max-w-[250px]" /> <button onClick={clearRecording} className="text-xs text-slate-500 hover:text-red-500 underline" > Recommencer </button> </div> )} </div> );}apps/admin/src/App.tsx+110-103
apps/admin/src/pages/LiveFeed.tsxAdded+376