feat: database-first refactor, unified architecture and visual developer manual

Summary of changes:
- Consolidated Studio+CMS and Experience+LMS into unified services.
- Moved core business logic (enrollment, grading, auth) to PostgreSQL functions.
- Implemented advanced auditing via DB triggers and session context.
- Added gamification (XP/Levels/Leaderboards) and logic encapsulation.
- Updated installation/diagnostic scripts for the new architecture.
- Created a comprehensive Visual Developer Manual in README.md with hardware scaling.
This commit is contained in:
2026-01-11 02:34:23 -03:00
parent a19da8de76
commit b1eb23926e
42 changed files with 2661 additions and 588 deletions
@@ -0,0 +1,194 @@
"use client";
import React, { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { cmsApi, Course, AdvancedAnalytics } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import {
LineChart,
BarChart3,
Users,
TrendingUp,
ArrowLeft,
Layers,
Calendar,
Filter
} from "lucide-react";
import CourseEditorLayout from "@/components/CourseEditorLayout";
export default function AdvancedAnalyticsPage() {
const { id } = useParams() as { id: string };
const router = useRouter();
const { user } = useAuth();
const [course, setCourse] = useState<Course | null>(null);
const [analytics, setAnalytics] = useState<AdvancedAnalytics | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
if (!user) return;
try {
const [courseData, advancedData] = await Promise.all([
cmsApi.getCourseWithFullOutline(id),
cmsApi.getAdvancedAnalytics(id)
]);
setCourse(courseData);
setAnalytics(advancedData);
} catch (err: any) {
console.error("Failed to load advanced analytics", err);
setError(err.message || "Failed to load data");
} finally {
setLoading(false);
}
};
fetchData();
}, [id, user]);
if (loading) return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="w-12 h-12 border-4 border-blue-500/20 border-t-blue-500 rounded-full animate-spin"></div>
</div>
);
if (error || !course || !analytics) return (
<div className="min-h-screen bg-[#0f1115] text-white p-20 text-center flex flex-col items-center justify-center gap-6">
<div className="text-gray-400">{error || "Data unavailable"}</div>
<button onClick={() => router.back()} className="btn-premium px-8">Go Back</button>
</div>
);
return (
<div className="min-h-screen bg-[#0f1115] text-white p-8">
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-12">
<div className="flex items-center gap-4">
<button
onClick={() => router.push(`/courses/${id}/analytics`)}
className="p-2 hover:bg-white/10 rounded-full transition-colors"
>
<ArrowLeft className="w-6 h-6" />
</button>
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-purple-400 to-indigo-400 bg-clip-text text-transparent">
Advanced Insights
</h1>
<p className="text-gray-400 mt-1">Cohort analysis and student retention for {course.title}</p>
</div>
</div>
</div>
<CourseEditorLayout activeTab="analytics">
<div className="p-8 space-y-12">
{/* Cohort Analysis */}
<section>
<div className="flex items-center justify-between mb-8">
<h2 className="text-2xl font-black flex items-center gap-3">
<Layers className="text-purple-500" />
Cohort Completion
</h2>
<div className="flex items-center gap-2 text-xs font-bold text-gray-500 uppercase tracking-widest bg-white/5 px-4 py-2 rounded-xl">
<Filter size={14} /> Grouped by Month
</div>
</div>
<div className="overflow-hidden rounded-3xl border border-white/10 bg-white/[0.02]">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-white/5">
<th className="p-6 text-xs font-black uppercase tracking-widest text-gray-500">Cohort (Enrollment Month)</th>
<th className="p-6 text-xs font-black uppercase tracking-widest text-gray-500">Students</th>
<th className="p-6 text-xs font-black uppercase tracking-widest text-gray-500">Avg. Completion Rate</th>
<th className="p-6 text-xs font-black uppercase tracking-widest text-gray-500">Engagement Status</th>
</tr>
</thead>
<tbody className="divide-y divide-white/5">
{analytics.cohorts.length === 0 ? (
<tr>
<td colSpan={4} className="p-12 text-center text-gray-600 italic">No cohort data available yet.</td>
</tr>
) : analytics.cohorts.map((cohort) => (
<tr key={cohort.period} className="hover:bg-white/[0.02] transition-colors">
<td className="p-6 font-bold flex items-center gap-3">
<Calendar size={16} className="text-purple-400" />
{cohort.period}
</td>
<td className="p-6 font-black">{cohort.count}</td>
<td className="p-6">
<div className="flex items-center gap-4">
<div className="flex-1 h-2 bg-white/5 rounded-full overflow-hidden min-w-[200px]">
<div
className="h-full bg-purple-500 transition-all duration-1000 shadow-[0_0_10px_rgba(168,85,247,0.5)]"
style={{ width: `${cohort.completion_rate * 100}%` }}
/>
</div>
<span className="text-sm font-black">{Math.round(cohort.completion_rate * 100)}%</span>
</div>
</td>
<td className="p-6">
{cohort.completion_rate > 0.8 ? (
<span className="text-[10px] font-black uppercase tracking-widest text-green-400 bg-green-400/10 px-3 py-1 rounded-full border border-green-500/20">Excellent</span>
) : cohort.completion_rate > 0.5 ? (
<span className="text-[10px] font-black uppercase tracking-widest text-blue-400 bg-blue-400/10 px-3 py-1 rounded-full border border-blue-500/20">Healthy</span>
) : (
<span className="text-[10px] font-black uppercase tracking-widest text-orange-400 bg-orange-400/10 px-3 py-1 rounded-full border border-orange-500/20">Low Momentum</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
{/* Retention Analysis */}
<section>
<h2 className="text-2xl font-black mb-8 flex items-center gap-3">
<TrendingUp className="text-indigo-500" />
Retention Heatmap
</h2>
<div className="space-y-6">
{analytics.retention.map((item, index) => {
const firstStudentCount = analytics.retention[0]?.student_count || 1;
const percentage = (item.student_count / firstStudentCount) * 100;
return (
<div key={item.lesson_id} className="group relative">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<div className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center text-[10px] font-black text-gray-500">
{index + 1}
</div>
<span className="font-bold text-gray-300">{item.lesson_title}</span>
</div>
<div className="text-right">
<div className="text-sm font-black text-white">{item.student_count} Students</div>
<div className="text-[10px] font-bold text-gray-600 uppercase tracking-widest">{Math.round(percentage)}% Retention</div>
</div>
</div>
<div className="h-4 w-full bg-white/5 rounded-lg overflow-hidden border border-white/5">
<div
className={`h-full transition-all duration-1000 ${percentage > 80 ? 'bg-indigo-500' :
percentage > 50 ? 'bg-indigo-600/70' :
'bg-indigo-700/40'
}`}
style={{ width: `${percentage}%` }}
/>
</div>
{index > 0 && analytics.retention[index - 1].student_count > 0 && (
<div className="absolute -top-4 right-0 text-[10px] font-black text-red-500/50">
-{Math.round(100 - (item.student_count / analytics.retention[index - 1].student_count) * 100)}% drop
</div>
)}
</div>
);
})}
</div>
</section>
</div>
</CourseEditorLayout>
</div>
</div>
);
}
@@ -11,7 +11,8 @@ import {
AlertTriangle,
ArrowLeft,
CheckCircle2,
BookOpen
BookOpen,
Layers
} from "lucide-react";
import CourseEditorLayout from "@/components/CourseEditorLayout";
@@ -100,8 +101,16 @@ export default function AnalyticsPage() {
<p className="text-gray-400 mt-1">Performance insights and student progress for {course?.title}</p>
</div>
</div>
<div className="bg-blue-500/20 text-blue-400 text-[10px] font-black uppercase tracking-wider px-2 py-1 rounded border border-blue-500/30">
{user?.role} View
<div className="flex items-center gap-4">
<button
onClick={() => router.push(`/courses/${id}/analytics/advanced`)}
className="btn-premium !bg-purple-600/10 !text-purple-400 border border-purple-500/20 hover:!bg-purple-600/20 !shadow-none gap-2 text-xs py-2"
>
<Layers size={14} /> Advanced Insights
</button>
<div className="bg-blue-500/20 text-blue-400 text-[10px] font-black uppercase tracking-wider px-2 py-1 rounded border border-blue-500/30">
{user?.role} View
</div>
</div>
</div>
@@ -0,0 +1,250 @@
"use client";
import React, { useState, useEffect } from "react";
import { cmsApi, Webhook, CreateWebhookPayload } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import {
Webhook as WebhookIcon,
Plus,
Trash2,
CheckCircle2,
AlertCircle,
Shield,
Globe,
Activity
} from "lucide-react";
import { Navbar } from "@/components/Navbar";
const AVAILABLE_EVENTS = [
{ id: 'course.published', label: 'Course Published', description: 'Triggered when a course is published to LMS' },
{ id: 'lesson.completed', label: 'Lesson Completed', description: 'Triggered when a student completes a lesson' },
{ id: 'user.enrolled', label: 'User Enrolled', description: 'Triggered when a user enrolls in a course' }
];
export default function WebhooksPage() {
const { user } = useAuth();
const [webhooks, setWebhooks] = useState<Webhook[]>([]);
const [loading, setLoading] = useState(true);
const [isAdding, setIsAdding] = useState(false);
const [newWebhook, setNewWebhook] = useState<CreateWebhookPayload>({
url: '',
events: ['course.published'],
secret: ''
});
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (user) {
fetchWebhooks();
}
}, [user]);
const fetchWebhooks = async () => {
try {
const data = await cmsApi.getWebhooks();
setWebhooks(data);
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
try {
await cmsApi.createWebhook(newWebhook);
setNewWebhook({ url: '', events: ['course.published'], secret: '' });
setIsAdding(false);
fetchWebhooks();
} catch (err: any) {
setError(err.message);
}
};
const handleDelete = async (id: string) => {
if (!confirm('Are you sure you want to delete this webhook?')) return;
try {
await cmsApi.deleteWebhook(id);
fetchWebhooks();
} catch (err: any) {
setError(err.message);
}
};
const toggleEvent = (eventId: string) => {
setNewWebhook(prev => ({
...prev,
events: prev.events.includes(eventId)
? prev.events.filter(e => e !== eventId)
: [...prev.events, eventId]
}));
};
if (loading) return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="w-12 h-12 border-4 border-blue-500/20 border-t-blue-500 rounded-full animate-spin"></div>
</div>
);
return (
<div className="min-h-screen bg-[#0f1115] text-white">
<Navbar />
<main className="max-w-5xl mx-auto pt-32 pb-20 px-6">
<div className="flex items-center justify-between mb-12">
<div>
<h1 className="text-4xl font-black mb-2 flex items-center gap-4">
<WebhookIcon size={40} className="text-blue-500" />
Enterprise Webhooks
</h1>
<p className="text-gray-400">Integrate OpenCCB with your external systems via HTTP callbacks.</p>
</div>
<button
onClick={() => setIsAdding(true)}
className="btn-premium flex items-center gap-2 px-6 py-3"
>
<Plus size={20} /> Add Webhook
</button>
</div>
{error && (
<div className="mb-8 p-4 bg-red-500/10 border border-red-500/20 rounded-2xl flex items-center gap-3 text-red-400" id="webhook-error">
<AlertCircle size={20} />
<span className="text-sm font-bold">{error}</span>
</div>
)}
{isAdding && (
<div className="mb-12 bg-white/5 border border-white/10 rounded-3xl p-8 overflow-hidden relative group">
<div className="absolute inset-0 bg-blue-500/5 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" />
<h2 className="text-xl font-black mb-6 flex items-center gap-2">
<Plus size={20} className="text-blue-400" />
Configure New Webhook
</h2>
<form onSubmit={handleCreate} className="space-y-6 relative">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-xs font-black text-gray-400 uppercase tracking-widest flex items-center gap-2">
<Globe size={14} /> Payload URL
</label>
<input
type="url"
id="webhook-url"
required
placeholder="https://your-api.com/webhooks"
className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-blue-500 transition-colors"
value={newWebhook.url}
onChange={e => setNewWebhook({ ...newWebhook, url: e.target.value })}
/>
</div>
<div className="space-y-2">
<label className="text-xs font-black text-gray-400 uppercase tracking-widest flex items-center gap-2">
<Shield size={14} /> Secret (HMAC-SHA256)
</label>
<input
type="text"
id="webhook-secret"
placeholder="Optional signing secret"
className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-blue-500 transition-colors"
value={newWebhook.secret}
onChange={e => setNewWebhook({ ...newWebhook, secret: e.target.value })}
/>
</div>
</div>
<div className="space-y-4">
<label className="text-xs font-black text-gray-400 uppercase tracking-widest flex items-center gap-2">
<Activity size={14} /> Events to Subscribe
</label>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{AVAILABLE_EVENTS.map(event => (
<div
key={event.id}
id={`event-${event.id}`}
onClick={() => toggleEvent(event.id)}
className={`p-4 rounded-2xl border transition-all cursor-pointer ${newWebhook.events.includes(event.id)
? 'bg-blue-500/20 border-blue-500 text-blue-400 shadow-[0_0_15px_rgba(59,130,246,0.1)]'
: 'bg-black/20 border-white/10 text-gray-400 hover:bg-white/5'
}`}
>
<div className="flex items-center justify-between mb-1">
<span className="font-bold">{event.label}</span>
{newWebhook.events.includes(event.id) && <CheckCircle2 size={16} />}
</div>
<p className="text-[10px] opacity-60 leading-relaxed font-medium">{event.description}</p>
</div>
))}
</div>
</div>
<div className="flex items-center justify-end gap-4 pt-4 border-t border-white/10">
<button
type="button"
onClick={() => setIsAdding(false)}
className="px-6 py-2 text-sm font-bold text-gray-400 hover:text-white transition-colors"
>
Cancel
</button>
<button type="submit" id="create-webhook-btn" className="btn-premium px-8 py-2">Create Webhook</button>
</div>
</form>
</div>
)}
<div className="space-y-6">
{webhooks.length === 0 && !isAdding ? (
<div className="text-center py-20 bg-white/5 border border-dashed border-white/10 rounded-3xl">
<WebhookIcon size={64} className="mx-auto text-gray-600 mb-6" />
<h3 className="text-xl font-bold text-gray-400">No webhooks configured</h3>
<p className="text-sm text-gray-500 mt-2">Add your first webhook to start receiving system notifications.</p>
</div>
) : (
webhooks.map(webhook => (
<div key={webhook.id} className="bg-white/5 border border-white/10 rounded-3xl p-8 flex items-center justify-between group hover:bg-white/[0.07] transition-all">
<div className="space-y-3">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center text-blue-400">
<Globe size={20} />
</div>
<div>
<h3 className="font-bold text-lg">{webhook.url}</h3>
<p className="text-xs text-gray-500">Created on {new Date(webhook.created_at).toLocaleDateString()}</p>
</div>
</div>
<div className="flex flex-wrap gap-2">
{webhook.events.map(event => (
<span key={event} className="text-[10px] font-black uppercase tracking-widest bg-blue-500/10 text-blue-400 px-3 py-1 rounded-full border border-blue-500/20">
{event}
</span>
))}
{webhook.secret && (
<span className="text-[10px] font-black uppercase tracking-widest bg-purple-500/10 text-purple-400 px-3 py-1 rounded-full border border-purple-500/20 flex items-center gap-1">
<Shield size={10} /> Signed
</span>
)}
</div>
</div>
<div className="flex items-center gap-4">
<div className="flex flex-col items-end mr-4">
<span className={`text-[10px] font-black uppercase tracking-widest ${webhook.is_active ? 'text-green-400' : 'text-gray-500'}`}>
{webhook.is_active ? 'Active' : 'Paused'}
</span>
<span className="text-[10px] font-bold text-gray-600">ID: {webhook.id.slice(0, 8)}...</span>
</div>
<button
onClick={() => handleDelete(webhook.id)}
className="delete-webhook-btn p-3 bg-red-500/10 text-red-400 rounded-2xl opacity-0 group-hover:opacity-100 hover:bg-red-500 hover:text-white transition-all transform hover:scale-110 shadow-lg"
title="Delete Webhook"
>
<Trash2 size={20} />
</button>
</div>
</div>
))
)}
</div>
</main>
</div>
);
}
+8 -1
View File
@@ -2,7 +2,7 @@
import Link from 'next/link';
import { useAuth } from '@/context/AuthContext';
import { LayoutDashboard, Building2, Users2, LogOut } from 'lucide-react';
import { LayoutDashboard, Building2, Users2, LogOut, Webhook } from 'lucide-react';
export function Navbar() {
const { user, logout } = useAuth();
@@ -42,6 +42,13 @@ export function Navbar() {
<Users2 className="w-4 h-4" />
Users
</Link>
<Link
href="/settings/webhooks"
className="text-sm font-medium text-gray-400 hover:text-blue-400 transition-colors flex items-center gap-2"
>
<Webhook className="w-4 h-4" />
Webhooks
</Link>
</>
)}
+40
View File
@@ -146,6 +146,40 @@ export interface CourseAnalytics {
}[];
}
export interface CohortData {
period: string;
count: number;
completion_rate: number;
}
export interface RetentionData {
lesson_id: string;
lesson_title: string;
student_count: number;
}
export interface AdvancedAnalytics {
cohorts: CohortData[];
retention: RetentionData[];
}
export interface Webhook {
id: string;
organization_id: string;
url: string;
events: string[];
secret?: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
export interface CreateWebhookPayload {
url: string;
events: string[];
secret?: string;
}
const getToken = () => typeof window !== 'undefined' ? localStorage.getItem('studio_token') : null;
const apiFetch = (url: string, options: RequestInit = {}) => {
@@ -212,11 +246,17 @@ export const cmsApi = {
// Admin & Analytics
getAuditLogs: (): Promise<AuditLog[]> => apiFetch('/audit-logs'),
getCourseAnalytics: (id: string): Promise<CourseAnalytics> => apiFetch(`/courses/${id}/analytics`),
getAdvancedAnalytics: (id: string): Promise<AdvancedAnalytics> => apiFetch(`/courses/${id}/analytics/advanced`),
// Users
getAllUsers: (): Promise<User[]> => apiFetch('/users'),
updateUser: (id: string, role: string, organization_id: string): Promise<void> => apiFetch(`/users/${id}`, { method: 'PUT', body: JSON.stringify({ role, organization_id }) }),
// Webhooks
getWebhooks: (): Promise<Webhook[]> => apiFetch('/webhooks'),
createWebhook: (payload: CreateWebhookPayload): Promise<Webhook> => apiFetch('/webhooks', { method: 'POST', body: JSON.stringify(payload) }),
deleteWebhook: (id: string): Promise<void> => apiFetch(`/webhooks/${id}`, { method: 'DELETE' }),
// Assets
uploadAsset: (file: File): Promise<UploadResponse> => {
const formData = new FormData();