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
+29 -12
View File
@@ -1,20 +1,37 @@
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
# Build stage for Rust LMS
FROM rustlang/rust:nightly AS rust-builder
WORKDIR /usr/src/app
COPY . .
RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/*
RUN cargo build --release -p lms-service
# Build stage for Next.js Experience
FROM node:18-alpine AS node-builder
WORKDIR /app
COPY web/experience/package*.json ./
RUN npm install
COPY web/experience/ .
RUN npm run build
# Production stage
# Final stage
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
ENV PORT 3003
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
# Install system dependencies for Rust binary
RUN apk add --no-cache openssl libgcc libstdc++
EXPOSE 3003
CMD ["node", "server.js"]
# Copy LMS binary
COPY --from=rust-builder /usr/src/app/target/release/lms-service ./
# Copy Experience frontend
COPY --from=node-builder /app/public ./public
COPY --from=node-builder /app/.next/standalone ./
COPY --from=node-builder /app/.next/static ./.next/static
# Copy entrypoint
COPY web/experience/entrypoint.sh ./
RUN chmod +x entrypoint.sh
EXPOSE 3003 3002
CMD ["./entrypoint.sh"]
-36
View File
@@ -1,36 +0,0 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Start the LMS backend in the background
./lms-service &
# Start the Experience frontend
node server.js
+65 -27
View File
@@ -5,13 +5,14 @@ import { lmsApi, Course, Lesson } from "@/lib/api";
import Link from "next/link";
import { useAuth } from "@/context/AuthContext";
import { useRouter } from "next/navigation";
import { Rocket, CheckCircle2, ArrowRight, Star, Calendar, Clock, AlertCircle } from "lucide-react";
import { Rocket, CheckCircle2, ArrowRight, Star, Calendar, Clock, AlertCircle, Zap, TrendingUp } from "lucide-react";
import Leaderboard from "@/components/Leaderboard";
export default function CatalogPage() {
const [courses, setCourses] = useState<Course[]>([]);
const [enrollments, setEnrollments] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [gamification, setGamification] = useState<{ points: number, badges: any[] } | null>(null);
const [gamification, setGamification] = useState<{ points: number, level: number, badges: any[] } | null>(null);
const [upcomingDeadlines, setUpcomingDeadlines] = useState<{ lesson: Lesson, courseTitle: string }[]>([]);
const { user } = useAuth();
@@ -106,34 +107,71 @@ export default function CatalogPage() {
</div>
{user && gamification && (
<div className="mb-16 grid grid-cols-1 md:grid-cols-3 gap-6 animate-in fade-in slide-in-from-top-6 duration-700">
<div className="md:col-span-1 glass-card p-8 bg-gradient-to-br from-blue-600/20 to-indigo-700/20 border-blue-500/20 flex flex-col items-center justify-center text-center rounded-3xl">
<div className="w-16 h-16 rounded-full bg-blue-500/10 flex items-center justify-center mb-4 border border-blue-500/20">
<Star className="text-blue-400 fill-blue-400/20" size={32} />
<div className="mb-16 grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in slide-in-from-top-6 duration-700">
<div className="lg:col-span-2 space-y-8">
<div className="glass-card p-10 bg-gradient-to-br from-blue-600/20 via-indigo-700/10 to-transparent border-blue-500/20 rounded-3xl relative overflow-hidden group">
<div className="relative z-10 flex flex-col md:flex-row md:items-center gap-10">
<div className="flex-shrink-0 relative">
<div className="w-24 h-24 rounded-3xl bg-blue-600 flex items-center justify-center shadow-2xl shadow-blue-500/40 rotate-3 group-hover:rotate-0 transition-transform duration-500">
<Zap className="text-white fill-white/20" size={48} />
</div>
<div className="absolute -bottom-2 -right-2 w-10 h-10 rounded-full bg-white text-black flex items-center justify-center font-black text-xs border-4 border-[#050505]">
{gamification.level}
</div>
</div>
<div className="flex-1 space-y-4">
<div>
<div className="text-[10px] font-black uppercase tracking-[0.3em] text-blue-400 mb-1">Current Standing</div>
<h2 className="text-3xl font-black text-white">Level {gamification.level} Pioneer</h2>
</div>
<div className="space-y-2">
<div className="flex justify-between items-end">
<div className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
{gamification.points} / {Math.pow(gamification.level, 2) * 100} XP
</div>
<div className="text-[10px] font-black text-blue-400 uppercase tracking-widest">
{Math.floor(((gamification.points - Math.pow(gamification.level - 1, 2) * 100) / (Math.pow(gamification.level, 2) * 100 - Math.pow(gamification.level - 1, 2) * 100)) * 100)}% to Level {gamification.level + 1}
</div>
</div>
<div className="h-2 w-full bg-white/5 rounded-full overflow-hidden border border-white/5">
<div
className="h-full bg-gradient-to-r from-blue-500 to-indigo-500 shadow-[0_0_20px_rgba(59,130,246,0.5)] transition-all duration-1000"
style={{ width: `${Math.min(100, Math.max(0, ((gamification.points - Math.pow(gamification.level - 1, 2) * 100) / (Math.pow(gamification.level, 2) * 100 - Math.pow(gamification.level - 1, 2) * 100)) * 100))}%` }}
></div>
</div>
</div>
</div>
</div>
{/* Background Flair */}
<div className="absolute -bottom-20 -right-20 w-64 h-64 bg-blue-500/10 blur-[120px] rounded-full pointer-events-none group-hover:bg-blue-500/20 transition-colors duration-500"></div>
</div>
<div className="glass-card p-8 bg-white/[0.01] border-white/5 rounded-3xl">
<h3 className="text-xs font-black uppercase tracking-widest text-gray-500 mb-6 flex items-center gap-2">
<CheckCircle2 size={14} /> My Badges
</h3>
<div className="flex flex-wrap gap-4">
{gamification.badges.length === 0 ? (
<p className="text-sm text-gray-600 italic">No badges earned yet. Start learning to unlock achievements!</p>
) : (
gamification.badges.map(badge => (
<div key={badge.id} className="group/badge relative">
<div className="w-14 h-14 rounded-2xl bg-gradient-to-tr from-amber-400/10 to-orange-500/10 border border-amber-500/20 flex items-center justify-center shadow-lg transition-all hover:scale-110 hover:bg-amber-500/20 cursor-help" title={badge.description}>
<span className="text-2xl">🏆</span>
</div>
<div className="absolute -bottom-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-[#050505] flex items-center justify-center text-[8px] font-bold"></div>
</div>
))
)}
</div>
</div>
<div className="text-4xl font-black text-white mb-1">{gamification.points}</div>
<div className="text-[10px] font-black uppercase tracking-[0.2em] text-blue-400">Total Experience Points</div>
</div>
<div className="md:col-span-2 glass-card p-8 bg-white/[0.01] border-white/5 rounded-3xl overflow-hidden relative">
<h3 className="text-xs font-black uppercase tracking-widest text-gray-500 mb-6 flex items-center gap-2">
<CheckCircle2 size={14} /> My Badges
</h3>
<div className="flex flex-wrap gap-4">
{gamification.badges.length === 0 ? (
<p className="text-sm text-gray-600 italic">No badges earned yet. Start learning to unlock achievements!</p>
) : (
gamification.badges.map(badge => (
<div key={badge.id} className="group/badge relative">
<div className="w-12 h-12 rounded-xl bg-gradient-to-tr from-amber-400/20 to-orange-500/20 border border-amber-500/30 flex items-center justify-center shadow-lg transition-transform hover:scale-110 cursor-help" title={badge.description}>
<span className="text-xl">🏆</span>
</div>
<div className="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-black flex items-center justify-center text-[8px] font-bold"></div>
</div>
))
)}
</div>
{/* Visual Flair */}
<div className="lg:col-span-1">
<Leaderboard />
</div>
</div>
)}
@@ -0,0 +1,77 @@
"use client";
import { useEffect, useState } from "react";
import { lmsApi, User } from "@/lib/api";
import { Trophy, Medal, Award } from "lucide-react";
export default function Leaderboard() {
const [topUsers, setTopUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchLeaderboard = async () => {
try {
const data = await lmsApi.getLeaderboard();
setTopUsers(data);
} catch (err) {
console.error("Failed to fetch leaderboard", err);
} finally {
setLoading(false);
}
};
fetchLeaderboard();
}, []);
if (loading) {
return <div className="animate-pulse space-y-4">
{[1, 2, 3].map(i => (
<div key={i} className="h-16 bg-white/5 rounded-2xl w-full"></div>
))}
</div>;
}
return (
<div className="glass-card p-8 border-white/5 bg-white/[0.01] rounded-3xl overflow-hidden relative">
<h3 className="text-xs font-black uppercase tracking-widest text-gray-500 mb-6 flex items-center gap-2">
<Trophy size={14} className="text-amber-500" /> Leaderboard
</h3>
<div className="space-y-3">
{topUsers.map((user, index) => (
<div
key={user.id}
className={`flex items-center gap-4 p-4 rounded-2xl transition-all ${index === 0 ? 'bg-gradient-to-r from-amber-500/10 to-transparent border border-amber-500/20 shadow-lg shadow-amber-500/5' :
'bg-white/5 border border-white/5 hover:bg-white/10'
}`}
>
<div className="flex-shrink-0 w-8 text-center font-black text-xs text-gray-600">
{index === 0 ? <Medal className="text-amber-500 mx-auto" size={18} /> :
index === 1 ? <Medal className="text-gray-400 mx-auto" size={18} /> :
index === 2 ? <Medal className="text-amber-700 mx-auto" size={18} /> :
index + 1}
</div>
<div className="flex-1">
<div className="text-sm font-bold text-gray-200 line-clamp-1">{user.full_name}</div>
<div className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">Level {user.level || 1}</div>
</div>
<div className="text-right">
<div className="text-sm font-black text-white">{user.xp || 0}</div>
<div className="text-[8px] font-black text-blue-500 uppercase tracking-widest">XP</div>
</div>
</div>
))}
{topUsers.length === 0 && (
<div className="text-center py-8 text-gray-600 italic text-sm">
No ranking data available yet.
</div>
)}
</div>
{/* Visual background flair */}
<div className="absolute -top-24 -right-24 w-48 h-48 bg-amber-500/10 blur-[100px] rounded-full pointer-events-none"></div>
</div>
);
}
+12 -1
View File
@@ -96,6 +96,8 @@ export interface User {
email: string;
full_name: string;
role: string;
xp?: number;
level?: number;
}
export interface AuthResponse {
@@ -187,12 +189,21 @@ export const lmsApi = {
return response.json();
},
async getGamification(userId: string): Promise<{ points: number, badges: { id: string, name: string, description: string }[] }> {
async getGamification(userId: string): Promise<{ points: number, level: number, badges: { id: string, name: string, description: string, earned_at: string }[] }> {
const response = await fetch(`${API_BASE_URL}/users/${userId}/gamification`);
if (!response.ok) throw new Error('Failed to fetch gamification data');
return response.json();
},
async getLeaderboard(): Promise<User[]> {
const token = localStorage.getItem('token');
const response = await fetch(`${API_BASE_URL}/analytics/leaderboard`, {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) throw new Error('Failed to fetch leaderboard');
return response.json();
},
async getBranding(orgId: string): Promise<Organization> {
const response = await fetch(`${CMS_API_URL}/organizations/${orgId}/branding`);
if (!response.ok) throw new Error('Failed to fetch branding');
+29 -11
View File
@@ -1,19 +1,37 @@
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
# Build stage for Rust CMS
FROM rustlang/rust:nightly AS rust-builder
WORKDIR /usr/src/app
COPY . .
RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/*
RUN cargo build --release -p cms-service
# Build stage for Next.js Studio
FROM node:18-alpine AS node-builder
WORKDIR /app
COPY web/studio/package*.json ./
RUN npm install
COPY web/studio/ .
RUN npm run build
# Production stage
# Final stage
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
# Install system dependencies for Rust binary
RUN apk add --no-cache openssl libgcc libstdc++
EXPOSE 3000
CMD ["node", "server.js"]
# Copy CMS binary
COPY --from=rust-builder /usr/src/app/target/release/cms-service ./
# Copy Studio frontend
COPY --from=node-builder /app/public ./public
COPY --from=node-builder /app/.next/standalone ./
COPY --from=node-builder /app/.next/static ./.next/static
# Copy entrypoint
COPY web/studio/entrypoint.sh ./
RUN chmod +x entrypoint.sh
EXPOSE 3000 3001
CMD ["./entrypoint.sh"]
-36
View File
@@ -1,36 +0,0 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Start the CMS backend in the background
./cms-service &
# Start the Studio frontend
node server.js
@@ -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();