feat: Implement course team management with dedicated UI and API, add course preview token generation, and refactor course settings UI.
This commit is contained in:
@@ -41,6 +41,7 @@ El proyecto ha sido optimizado para reducir la complejidad de la infraestructura
|
||||
- **Student Notes**: Sistema de anotaciones personales por lección con auto-guardado inteligente (debounced).
|
||||
- **Interactive Gradebook**: Libro de calificaciones avanzado con filtrado por cohortes, exportación masiva a CSV con desgloses por categoría y pertenencia a cohortes.
|
||||
- **Bulk Operations**: Herramientas administrativas para inscripción masiva de usuarios vía email y comunicación segmentada.
|
||||
- **Course Teams (Multi-instructor support)**
|
||||
- **Segmented Announcements**: Sistema de anuncios con capacidad de dirigirse a cohortes específicas y notificaciones filtradas.
|
||||
- **Content Libraries**: Repositorio centralizado de bloques y lecciones reutilizables entre múltiples cursos.
|
||||
- **Advanced Grading (Rubrics)**: Sistema de evaluación basado en rúbricas detalladas con indicadores de desempeño por criterio.
|
||||
|
||||
+3
-2
@@ -104,6 +104,7 @@
|
||||
- [x] **Mejoras en la Gestión de Cursos**:
|
||||
- [x] Nombrado manual de módulos, lecciones y actividades
|
||||
- [x] Pacing de cursos: Modo autodidacta (Evergreen) o Dirigido por instructor (Cohort)
|
||||
|
||||
- [x] Calendario de hitos y recordatorios automáticos de fechas límite
|
||||
|
||||
## Fase 8: Funcionalidades Enterprise (En Progreso)
|
||||
@@ -186,8 +187,8 @@
|
||||
- [x] **Content Libraries**: Repositorio reutilizable de bloques y lecciones.
|
||||
- [x] **Advanced Grading**: Rúbricas detalladas y workflows de calificación.
|
||||
- [x] **Learning Sequences**: Prerequisitos y rutas condicionales entre lecciones.
|
||||
- [x] **Bulk Operations**: Inscripción masiva, exportación de calificaciones, comunicación masiva. ✅
|
||||
- [ ] **Course Teams**: Múltiples instructores con roles y permisos granulares.
|
||||
- [x] **Bulk Operations**: Bulk enrollment, advanced grade export, and segmented announcements.
|
||||
- [x] **Course Teams**: Support for multiple instructors per course with granular roles.
|
||||
- [ ] **Course Preview**: Vista previa de lecciones sin inscripción.
|
||||
- [ ] **Bookmarks**: Sistema de favoritos para lecciones importantes.
|
||||
- [ ] **Progress Dashboard**: Gráficos de progreso temporal y predicción de finalización.
|
||||
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
};
|
||||
use bcrypt::{DEFAULT_COST, hash, verify};
|
||||
use chrono::{DateTime, Utc};
|
||||
use common::auth::{Claims, create_jwt};
|
||||
use common::auth::{Claims, create_jwt, create_preview_token};
|
||||
use common::middleware::Org;
|
||||
use common::models::{
|
||||
AuthResponse, Course, CourseAnalytics, Lesson, Module, Organization, PublishedCourse,
|
||||
@@ -120,6 +120,7 @@ pub async fn publish_course(
|
||||
organization,
|
||||
grading_categories,
|
||||
modules: pub_modules,
|
||||
dependencies: None,
|
||||
};
|
||||
|
||||
// 4. Send to LMS
|
||||
@@ -3288,6 +3289,164 @@ pub async fn import_course(
|
||||
Ok(Json(new_course))
|
||||
}
|
||||
|
||||
pub async fn check_course_access(
|
||||
pool: &PgPool,
|
||||
course_id: Uuid,
|
||||
user_id: Uuid,
|
||||
role: &str,
|
||||
) -> Result<bool, (StatusCode, String)> {
|
||||
if role == "admin" {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let exists = sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM course_instructors WHERE course_id = $1 AND user_id = $2)"
|
||||
)
|
||||
.bind(course_id)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(exists)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, sqlx::FromRow)]
|
||||
pub struct CourseInstructor {
|
||||
pub id: Uuid,
|
||||
pub course_id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub role: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub email: String,
|
||||
pub full_name: String,
|
||||
}
|
||||
|
||||
pub async fn get_course_team(
|
||||
Org(_org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Vec<CourseInstructor>>, (StatusCode, String)> {
|
||||
if !check_course_access(&pool, id, claims.sub, &claims.role).await? {
|
||||
return Err((StatusCode::FORBIDDEN, "No access to this course team".into()));
|
||||
}
|
||||
|
||||
let team = sqlx::query_as::<_, CourseInstructor>(
|
||||
"SELECT ci.*, u.email, u.full_name FROM course_instructors ci
|
||||
JOIN users u ON ci.user_id = u.id
|
||||
WHERE ci.course_id = $1"
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(Json(team))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct AddTeamMemberPayload {
|
||||
pub email: String,
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
pub async fn add_team_member(
|
||||
Org(_org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(payload): Json<AddTeamMemberPayload>,
|
||||
) -> Result<Json<CourseInstructor>, (StatusCode, String)> {
|
||||
// Only primary instructors or admins can add members
|
||||
let is_authorized = if claims.role == "admin" {
|
||||
true
|
||||
} else {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM course_instructors WHERE course_id = $1 AND user_id = $2 AND role = 'primary')"
|
||||
)
|
||||
.bind(id)
|
||||
.bind(claims.sub)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
};
|
||||
|
||||
if !is_authorized {
|
||||
return Err((StatusCode::FORBIDDEN, "Only primary instructors can add team members".into()));
|
||||
}
|
||||
|
||||
let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
|
||||
.bind(&payload.email)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|_| (StatusCode::NOT_FOUND, "User not found".into()))?;
|
||||
|
||||
let instructor = sqlx::query_as::<_, CourseInstructor>(
|
||||
"INSERT INTO course_instructors (course_id, user_id, role)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *, (SELECT email FROM users WHERE id = $2) as email, (SELECT full_name FROM users WHERE id = $2) as full_name"
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&payload.role)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
|
||||
|
||||
Ok(Json(instructor))
|
||||
}
|
||||
|
||||
pub async fn remove_team_member(
|
||||
Org(_org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Path((course_id, user_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
let is_authorized = if claims.role == "admin" {
|
||||
true
|
||||
} else {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM course_instructors WHERE course_id = $1 AND user_id = $2 AND role = 'primary')"
|
||||
)
|
||||
.bind(course_id)
|
||||
.bind(claims.sub)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
};
|
||||
|
||||
if !is_authorized && claims.sub != user_id {
|
||||
return Err((StatusCode::FORBIDDEN, "Unauthorized to remove this member".into()));
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM course_instructors WHERE course_id = $1 AND user_id = $2")
|
||||
.bind(course_id)
|
||||
.bind(user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn create_course_preview_token(
|
||||
Org(_org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
|
||||
// Verify user has access to this course (must be an instructor/admin)
|
||||
if !check_course_access(&pool, id, claims.sub, &claims.role).await? {
|
||||
return Err((StatusCode::FORBIDDEN, "No access to this course preview".into()));
|
||||
}
|
||||
|
||||
let token = create_preview_token(claims.sub, claims.org, id)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(Json(json!({ "token": token })))
|
||||
}
|
||||
|
||||
// --- AI Course Generation ---
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -3540,7 +3699,7 @@ pub async fn delete_course(
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
|
||||
// 2. Additional permission check for instructors
|
||||
if !is_super_admin && claims.role == "instructor" && course.instructor_id != claims.sub {
|
||||
if !is_super_admin && !check_course_access(&pool, course.id, claims.sub, &claims.role).await? {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,18 @@ async fn main() {
|
||||
"/courses/{id}/analytics/advanced",
|
||||
get(handlers::get_advanced_analytics),
|
||||
)
|
||||
.route(
|
||||
"/courses/{id}/team",
|
||||
get(handlers::get_course_team).post(handlers::add_team_member),
|
||||
)
|
||||
.route(
|
||||
"/courses/{id}/team/{user_id}",
|
||||
delete(handlers::remove_team_member),
|
||||
)
|
||||
.route(
|
||||
"/courses/{id}/preview-token",
|
||||
post(handlers::create_course_preview_token),
|
||||
)
|
||||
.route("/lessons/{id}/heatmap", get(handlers::get_lesson_heatmap))
|
||||
.route(
|
||||
"/modules",
|
||||
|
||||
@@ -734,10 +734,32 @@ pub async fn ingest_course(
|
||||
|
||||
pub async fn get_course_outline(
|
||||
Org(org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<common::models::PublishedCourse>, StatusCode> {
|
||||
tracing::info!("get_course_outline: id={}, caller_org={}", id, org_ctx.id);
|
||||
tracing::info!(
|
||||
"get_course_outline: id={}, user={}, caller_org={}",
|
||||
id,
|
||||
claims.sub,
|
||||
org_ctx.id
|
||||
);
|
||||
|
||||
// If it's a preview token, ensure it's for the correct course
|
||||
if claims.token_type.as_deref() == Some("preview") {
|
||||
if claims.course_id != Some(id) {
|
||||
tracing::warn!(
|
||||
"get_course_outline: Preview token course_id mismatch. Token for {:?}, requested {}",
|
||||
claims.course_id,
|
||||
id
|
||||
);
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
tracing::info!(
|
||||
"get_course_outline: Authorized via preview token for course {}",
|
||||
id
|
||||
);
|
||||
}
|
||||
// 1. Fetch Course
|
||||
let course = sqlx::query_as::<_, Course>("SELECT * FROM courses WHERE id = $1")
|
||||
.bind(id)
|
||||
@@ -857,35 +879,59 @@ pub async fn get_lesson_content(
|
||||
claims.sub
|
||||
);
|
||||
|
||||
// 1. Check if user is enrolled in the course this lesson belongs to
|
||||
let lesson = sqlx::query_as::<_, Lesson>(
|
||||
"SELECT l.* FROM lessons l
|
||||
JOIN modules m ON l.module_id = m.id
|
||||
JOIN enrollments e ON m.course_id = e.course_id
|
||||
WHERE l.id = $1 AND e.user_id = $2",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(claims.sub)
|
||||
.fetch_optional(&pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("get_lesson_content: DB error: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
// 1. Check for preview token override
|
||||
let is_preview = claims.token_type.as_deref() == Some("preview");
|
||||
|
||||
let lesson = if is_preview {
|
||||
tracing::info!("get_lesson_content: Using preview token for lesson {}", id);
|
||||
// Ensure the preview token is for the correct course (if we want to be strict)
|
||||
// or just fetch the lesson and verify it belongs to the same org.
|
||||
sqlx::query_as::<_, Lesson>(
|
||||
"SELECT l.* FROM lessons l
|
||||
JOIN modules m ON l.module_id = m.id
|
||||
WHERE l.id = $1 AND l.organization_id = $2",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(claims.org)
|
||||
.fetch_optional(&pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("get_lesson_content: DB error (preview): {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
} else {
|
||||
sqlx::query_as::<_, Lesson>(
|
||||
"SELECT l.* FROM lessons l
|
||||
JOIN modules m ON l.module_id = m.id
|
||||
JOIN enrollments e ON m.course_id = e.course_id
|
||||
WHERE l.id = $1 AND e.user_id = $2",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(claims.sub)
|
||||
.fetch_optional(&pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("get_lesson_content: DB error: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
};
|
||||
|
||||
let lesson = match lesson {
|
||||
Some(l) => l,
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"get_lesson_content: User {} not enrolled or lesson {} not found",
|
||||
claims.sub,
|
||||
id
|
||||
"get_lesson_content: Access denied or lesson {} not found (is_preview={})",
|
||||
id,
|
||||
is_preview
|
||||
);
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Enforce Prerequisites
|
||||
// 2. Enforce Prerequisites (Skip for previews)
|
||||
if is_preview {
|
||||
return Ok(Json(lesson));
|
||||
}
|
||||
// We check if there are any prerequisites that the user hasn't completed yet.
|
||||
// A prerequisite is completed if:
|
||||
// a) It's graded and the user has a grade >= min_score_percentage (default 0)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use jsonwebtoken::{encode, Header, EncodingKey};
|
||||
use chrono::{Duration, Utc};
|
||||
use jsonwebtoken::{EncodingKey, Header, encode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use chrono::{Utc, Duration};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Claims {
|
||||
@@ -9,9 +9,15 @@ pub struct Claims {
|
||||
pub org: Uuid,
|
||||
pub exp: i64,
|
||||
pub role: String,
|
||||
pub course_id: Option<Uuid>,
|
||||
pub token_type: Option<String>, // "access", "preview"
|
||||
}
|
||||
|
||||
pub fn create_jwt(user_id: Uuid, organization_id: Uuid, role: &str) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
pub fn create_jwt(
|
||||
user_id: Uuid,
|
||||
organization_id: Uuid,
|
||||
role: &str,
|
||||
) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
let expiration = Utc::now()
|
||||
.checked_add_signed(Duration::hours(24))
|
||||
.expect("valid timestamp")
|
||||
@@ -22,8 +28,41 @@ pub fn create_jwt(user_id: Uuid, organization_id: Uuid, role: &str) -> Result<St
|
||||
org: organization_id,
|
||||
exp: expiration,
|
||||
role: role.to_string(),
|
||||
course_id: None,
|
||||
token_type: Some("access".to_string()),
|
||||
};
|
||||
|
||||
let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "secret".to_string());
|
||||
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref()))
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claims,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn create_preview_token(
|
||||
user_id: Uuid,
|
||||
organization_id: Uuid,
|
||||
course_id: Uuid,
|
||||
) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
let expiration = Utc::now()
|
||||
.checked_add_signed(Duration::hours(1))
|
||||
.expect("valid timestamp")
|
||||
.timestamp();
|
||||
|
||||
let claims = Claims {
|
||||
sub: user_id,
|
||||
org: organization_id,
|
||||
exp: expiration,
|
||||
role: "instructor".to_string(),
|
||||
course_id: Some(course_id),
|
||||
token_type: Some("preview".to_string()),
|
||||
};
|
||||
|
||||
let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "secret".to_string());
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claims,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -26,16 +26,27 @@ pub async fn org_extractor_middleware(
|
||||
.and_then(|header: &axum::http::HeaderValue| header.to_str().ok());
|
||||
|
||||
let token = if let Some(token_str) = auth_header.and_then(|s: &str| s.strip_prefix("Bearer ")) {
|
||||
token_str
|
||||
token_str.to_string()
|
||||
} else {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
// Check for preview_token in query string
|
||||
let query = req.uri().query().unwrap_or_default();
|
||||
let preview_token = query
|
||||
.split('&')
|
||||
.find(|part| part.starts_with("preview_token="))
|
||||
.and_then(|part| part.split('=').nth(1));
|
||||
|
||||
if let Some(token) = preview_token {
|
||||
token.to_string()
|
||||
} else {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
};
|
||||
|
||||
// NOTA: El secreto debe venir de una variable de entorno en producción.
|
||||
let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "secret".to_string());
|
||||
|
||||
let mut claims = decode::<Claims>(
|
||||
token,
|
||||
&token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)
|
||||
|
||||
@@ -32,7 +32,15 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
|
||||
setUserGrades(grades);
|
||||
|
||||
const enrollmentData = await lmsApi.getEnrollments(user.id);
|
||||
setIsEnrolled(enrollmentData.some(e => e.course_id === params.id));
|
||||
const enrolled = enrollmentData.some(e => e.course_id === params.id);
|
||||
|
||||
// Allow preview token to override enrollment status
|
||||
const isPreview = typeof window !== 'undefined' && !!sessionStorage.getItem('preview_token');
|
||||
setIsEnrolled(enrolled || isPreview);
|
||||
} else {
|
||||
// Even if not logged in, if there's a preview token, consider "enrolled" for UI
|
||||
const isPreview = typeof window !== 'undefined' && !!sessionStorage.getItem('preview_token');
|
||||
if (isPreview) setIsEnrolled(true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
@@ -346,7 +346,20 @@ export interface UpdateAnnouncementPayload {
|
||||
|
||||
|
||||
|
||||
const getToken = () => typeof window !== 'undefined' ? localStorage.getItem('experience_token') : null;
|
||||
const getToken = () => {
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
// Check for preview token in URL
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const previewToken = urlParams.get('preview_token');
|
||||
|
||||
if (previewToken) {
|
||||
sessionStorage.setItem('preview_token', previewToken);
|
||||
return previewToken;
|
||||
}
|
||||
|
||||
return sessionStorage.getItem('preview_token') || localStorage.getItem('experience_token');
|
||||
};
|
||||
|
||||
const apiFetch = async (url: string, options: RequestInit = {}, isCMS: boolean = false) => {
|
||||
const token = getToken();
|
||||
|
||||
@@ -246,8 +246,20 @@ export default function CourseEditor({ params }: { params: { id: string } }) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button className="flex items-center gap-2 px-6 py-3 glass hover:bg-white/20 transition-all rounded-xl text-sm font-bold shadow-lg active:scale-95">
|
||||
Preview
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const { token } = await cmsApi.getPreviewToken(params.id);
|
||||
const expUrl = process.env.NEXT_PUBLIC_EXPERIENCE_URL || "http://localhost:3000";
|
||||
window.open(`${expUrl}/courses/${params.id}?preview_token=${token}`, "_blank");
|
||||
} catch (err) {
|
||||
console.error("Failed to get preview token", err);
|
||||
alert("Failed to start preview.");
|
||||
}
|
||||
}}
|
||||
className="flex items-center gap-2 px-6 py-3 glass hover:bg-white/20 transition-all rounded-xl text-sm font-bold shadow-lg active:scale-95"
|
||||
>
|
||||
<PlayCircle size={18} /> Preview
|
||||
</button>
|
||||
<button
|
||||
onClick={handlePublish}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { cmsApi, CourseInstructor } from "@/lib/api";
|
||||
import { Users, UserPlus, Trash2, Shield, User, Loader2, Mail } from "lucide-react";
|
||||
|
||||
interface TeamManagementSectionProps {
|
||||
courseId: string;
|
||||
}
|
||||
|
||||
export default function TeamManagementSection({ courseId }: TeamManagementSectionProps) {
|
||||
const [team, setTeam] = useState<CourseInstructor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [role, setRole] = useState("instructor");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchTeam = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await cmsApi.getCourseTeam(courseId);
|
||||
setTeam(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load team", err);
|
||||
setError("Failed to load course team");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchTeam();
|
||||
}, [courseId]);
|
||||
|
||||
const handleAddMember = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!email) return;
|
||||
|
||||
setAdding(true);
|
||||
setError(null);
|
||||
try {
|
||||
await cmsApi.addTeamMember(courseId, email, role);
|
||||
setEmail("");
|
||||
fetchTeam();
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
setError(err.message || "Failed to add team member. Make sure the user exists.");
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveMember = async (userId: string) => {
|
||||
if (!confirm("Are you sure you want to remove this instructor?")) return;
|
||||
|
||||
try {
|
||||
await cmsApi.removeTeamMember(courseId, userId);
|
||||
fetchTeam();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert("Failed to remove team member");
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8 space-y-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 rounded-2xl bg-blue-500/10 flex items-center justify-center text-blue-400">
|
||||
<Users size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-black">Course Team</h2>
|
||||
<p className="text-sm text-gray-400">Manage instructors and assistants for this course</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add Member Form */}
|
||||
<form onSubmit={handleAddMember} className="bg-white/5 border border-white/10 rounded-2xl p-6">
|
||||
<h3 className="text-sm font-bold text-gray-300 mb-4 flex items-center gap-2">
|
||||
<UserPlus size={16} /> Add Team Member
|
||||
</h3>
|
||||
<div className="flex flex-col md:flex-row gap-4">
|
||||
<div className="flex-1 relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="instructor@example.com"
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:border-blue-500 transition-colors"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
className="bg-black/30 border border-white/10 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-blue-500 transition-colors"
|
||||
>
|
||||
<option value="instructor">Instructor</option>
|
||||
<option value="assistant">Assistant</option>
|
||||
<option value="primary">Primary Instructor</option>
|
||||
</select>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={adding}
|
||||
className="bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white font-bold px-6 py-2 rounded-xl text-sm transition-all active:scale-95 flex items-center gap-2"
|
||||
>
|
||||
{adding ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus size={16} />}
|
||||
Add Member
|
||||
</button>
|
||||
</div>
|
||||
{error && <p className="mt-3 text-xs text-red-400 font-medium">{error}</p>}
|
||||
</form>
|
||||
|
||||
{/* Member List */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-bold text-gray-300">Active Instructors</h3>
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
{team.map((member) => (
|
||||
<div key={member.user_id} className="flex items-center justify-between p-4 bg-white/5 border border-white/10 rounded-2xl hover:bg-white/[0.07] transition-colors">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-10 h-10 rounded-full bg-gradient-to-tr from-blue-500 to-indigo-500 flex items-center justify-center text-white font-bold text-sm shadow-lg shadow-blue-500/10">
|
||||
{member.full_name.charAt(0)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-bold flex items-center gap-2">
|
||||
{member.full_name}
|
||||
{member.role === 'primary' && (
|
||||
<span className="px-2 py-0.5 bg-blue-500/10 border border-blue-500/20 rounded text-[10px] text-blue-400 font-bold uppercase tracking-wider">
|
||||
Primary
|
||||
</span>
|
||||
)}
|
||||
{member.role === 'assistant' && (
|
||||
<span className="px-2 py-0.5 bg-gray-500/10 border border-gray-500/20 rounded text-[10px] text-gray-400 font-bold uppercase tracking-wider">
|
||||
Assistant
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{member.email}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{member.role !== 'primary' && (
|
||||
<button
|
||||
onClick={() => handleRemoveMember(member.user_id)}
|
||||
className="p-2 text-gray-500 hover:text-red-400 hover:bg-red-400/10 rounded-lg transition-all"
|
||||
title="Remove member"
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{team.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500 text-sm">
|
||||
No instructors added yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ const DEFAULT_CERTIFICATE_TEMPLATE = `
|
||||
`;
|
||||
|
||||
import CourseEditorLayout from "@/components/CourseEditorLayout";
|
||||
import TeamManagementSection from "./TeamManagementSection";
|
||||
|
||||
export default function CourseSettingsPage() {
|
||||
const { id } = useParams() as { id: string };
|
||||
@@ -164,286 +165,289 @@ export default function CourseSettingsPage() {
|
||||
</div>
|
||||
|
||||
<CourseEditorLayout activeTab="settings">
|
||||
<div className="space-y-8">
|
||||
<TeamManagementSection courseId={id} />
|
||||
|
||||
{/* Passing Percentage Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-purple-500/10 flex items-center justify-center text-purple-400">
|
||||
<SettingsIcon size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Grading Configuration</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-3">
|
||||
Passing Percentage
|
||||
</label>
|
||||
<div className="flex items-center gap-6">
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="100"
|
||||
value={passingPercentage}
|
||||
onChange={(e) => setPassingPercentage(parseInt(e.target.value))}
|
||||
className="flex-1 h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||
/>
|
||||
<div className="text-4xl font-black text-blue-400 w-24 text-right">
|
||||
{passingPercentage}%
|
||||
</div>
|
||||
{/* Passing Percentage Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-purple-500/10 flex items-center justify-center text-purple-400">
|
||||
<SettingsIcon size={24} />
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-3">
|
||||
Students must achieve at least this percentage to pass the course.
|
||||
</p>
|
||||
<h2 className="text-2xl font-black">Grading Configuration</h2>
|
||||
</div>
|
||||
|
||||
{/* Performance Tiers Preview */}
|
||||
<div className="bg-white/5 border border-white/10 rounded-2xl p-6">
|
||||
<h3 className="text-sm font-bold text-gray-300 mb-4">Performance Tiers Preview</h3>
|
||||
<div className="space-y-3 text-xs">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-red-500 rounded"></div>
|
||||
<span className="text-red-400 font-bold">Reprobado:</span>
|
||||
<span className="text-gray-400">0% - {Math.max(0, passingPercentage - 1)}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-orange-500 rounded"></div>
|
||||
<span className="text-orange-400 font-bold">Rendimiento Bajo:</span>
|
||||
<span className="text-gray-400">{passingPercentage}% - {passingPercentage + 9}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-yellow-500 rounded"></div>
|
||||
<span className="text-yellow-400 font-bold">Rendimiento Medio:</span>
|
||||
<span className="text-gray-400">{passingPercentage + 10}% - {passingPercentage + 15}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-green-500 rounded"></div>
|
||||
<span className="text-green-400 font-bold">Buen Rendimiento:</span>
|
||||
<span className="text-gray-400">{passingPercentage + 16}% - 90%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-blue-500 rounded"></div>
|
||||
<span className="text-blue-400 font-bold">Excelente:</span>
|
||||
<span className="text-gray-400">91% - 100%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Course Pacing Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-green-500/10 flex items-center justify-center text-green-400">
|
||||
<Clock size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Pacing & Schedule</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Pacing Mode</label>
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
onClick={() => setPacingMode('self_paced')}
|
||||
className={`flex-1 p-4 rounded-2xl border-2 transition-all text-left ${pacingMode === 'self_paced' ? 'border-blue-500 bg-blue-500/10' : 'border-white/5 bg-white/5 hover:border-white/10'}`}
|
||||
>
|
||||
<div className="font-bold">Self-Paced</div>
|
||||
<div className="text-xs text-gray-500">Learners go at their own speed.</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPacingMode('instructor_led')}
|
||||
className={`flex-1 p-4 rounded-2xl border-2 transition-all text-left ${pacingMode === 'instructor_led' ? 'border-purple-500 bg-purple-500/10' : 'border-white/5 bg-white/5 hover:border-white/10'}`}
|
||||
>
|
||||
<div className="font-bold">Instructor-Led</div>
|
||||
<div className="text-xs text-gray-500">Cohort-based with specific dates.</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pacingMode === 'instructor_led' && (
|
||||
<div className="space-y-4 animate-in fade-in slide-in-from-top-2">
|
||||
<label className="block text-sm font-bold text-gray-300">Course Schedule</label>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs text-gray-500">Start Date</label>
|
||||
<div className="relative">
|
||||
<Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs text-gray-500">End Date</label>
|
||||
<div className="relative">
|
||||
<Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Course Pricing Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-blue-500/10 flex items-center justify-center text-blue-400">
|
||||
<span className="text-xl font-bold">$</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Pricing</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Price</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(parseFloat(e.target.value))}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-3 px-4 text-white focus:outline-none focus:border-blue-500 transition-colors"
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<div className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 font-bold">
|
||||
{currency}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">Set to 0 for a free course.</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Currency</label>
|
||||
<select
|
||||
value={currency}
|
||||
onChange={(e) => setCurrency(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-3 px-4 text-white focus:outline-none focus:border-blue-500 transition-colors appearance-none"
|
||||
>
|
||||
<option value="USD">USD - US Dollar</option>
|
||||
<option value="CLP">CLP - Chilean Peso</option>
|
||||
<option value="ARS">ARS - Argentine Peso</option>
|
||||
<option value="BRL">BRL - Brazilian Real</option>
|
||||
<option value="MXN">MXN - Mexican Peso</option>
|
||||
<option value="COP">COP - Colombian Peso</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Certificate Template Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-400">
|
||||
<BookOpen size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Certificate Template</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<p className="text-gray-400">
|
||||
Design the HTML certificate that students will receive upon passing the course.
|
||||
Available variables: <code className="text-blue-400">{"{{student_name}}"}</code>, <code className="text-blue-400">{"{{course_title}}"}</code>, <code className="text-blue-400">{"{{date}}"}</code>, <code className="text-blue-400">{"{{score}}"}</code>.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-300">HTML Template</label>
|
||||
<textarea
|
||||
value={certificateTemplate}
|
||||
onChange={(e) => setCertificateTemplate(e.target.value)}
|
||||
className="w-full h-[400px] bg-black/30 border border-white/10 rounded-xl p-4 font-mono text-sm text-gray-300 focus:outline-none focus:border-blue-500 transition-colors resize-none"
|
||||
placeholder="Enter HTML code here..."
|
||||
/>
|
||||
<button
|
||||
onClick={() => setCertificateTemplate(DEFAULT_CERTIFICATE_TEMPLATE)}
|
||||
className="text-xs text-blue-400 hover:text-blue-300 underline"
|
||||
>
|
||||
Reset to Default Template
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-300">Live Preview</label>
|
||||
<div className="w-full h-[400px] bg-white rounded-xl overflow-hidden relative group">
|
||||
<iframe
|
||||
srcDoc={certificateTemplate
|
||||
.replace(/{{student_name}}/g, "Jane Doe")
|
||||
.replace(/{{course_title}}/g, course?.title || "Demo Course")
|
||||
.replace(/{{date}}/g, new Date().toLocaleDateString())
|
||||
.replace(/{{score}}/g, "95")
|
||||
}
|
||||
className="w-full h-full transform scale-75 origin-top-left w-[133%] h-[133%]"
|
||||
style={{ border: "none" }}
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-3">
|
||||
Passing Percentage
|
||||
</label>
|
||||
<div className="flex items-center gap-6">
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="100"
|
||||
value={passingPercentage}
|
||||
onChange={(e) => setPassingPercentage(parseInt(e.target.value))}
|
||||
className="flex-1 h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 pointer-events-none transition-colors" />
|
||||
<div className="text-4xl font-black text-blue-400 w-24 text-right">
|
||||
{passingPercentage}%
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-3">
|
||||
Students must achieve at least this percentage to pass the course.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Performance Tiers Preview */}
|
||||
<div className="bg-white/5 border border-white/10 rounded-2xl p-6">
|
||||
<h3 className="text-sm font-bold text-gray-300 mb-4">Performance Tiers Preview</h3>
|
||||
<div className="space-y-3 text-xs">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-red-500 rounded"></div>
|
||||
<span className="text-red-400 font-bold">Reprobado:</span>
|
||||
<span className="text-gray-400">0% - {Math.max(0, passingPercentage - 1)}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-orange-500 rounded"></div>
|
||||
<span className="text-orange-400 font-bold">Rendimiento Bajo:</span>
|
||||
<span className="text-gray-400">{passingPercentage}% - {passingPercentage + 9}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-yellow-500 rounded"></div>
|
||||
<span className="text-yellow-400 font-bold">Rendimiento Medio:</span>
|
||||
<span className="text-gray-400">{passingPercentage + 10}% - {passingPercentage + 15}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-green-500 rounded"></div>
|
||||
<span className="text-green-400 font-bold">Buen Rendimiento:</span>
|
||||
<span className="text-gray-400">{passingPercentage + 16}% - 90%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-16 h-4 bg-blue-500 rounded"></div>
|
||||
<span className="text-blue-400 font-bold">Excelente:</span>
|
||||
<span className="text-gray-400">91% - 100%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{/* Course Portability Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-amber-500/10 flex items-center justify-center text-amber-400">
|
||||
<Download size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Portability</h2>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-bold text-gray-300">Export Course</h3>
|
||||
<p className="text-xs text-gray-500">
|
||||
Download the entire course structure, modules, and lessons as a JSON file.
|
||||
You can use this to backup or move content between organizations.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleExport}
|
||||
disabled={exporting}
|
||||
className="flex items-center gap-2 px-6 py-3 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl font-bold transition-all active:scale-95 disabled:opacity-50"
|
||||
>
|
||||
<Download size={18} />
|
||||
{exporting ? "Exporting..." : "Download JSON"}
|
||||
</button>
|
||||
{/* Course Pacing Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-green-500/10 flex items-center justify-center text-green-400">
|
||||
<Clock size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Pacing & Schedule</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-bold text-gray-300">Import Course</h3>
|
||||
<p className="text-xs text-gray-500">
|
||||
Upload a previously exported course JSON file. This will create a NEW course
|
||||
within the current organization based on that data.
|
||||
</p>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleImport}
|
||||
disabled={importing}
|
||||
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
|
||||
/>
|
||||
<button
|
||||
disabled={importing}
|
||||
className="flex items-center gap-2 px-6 py-3 bg-indigo-600/20 hover:bg-indigo-600/30 border border-indigo-500/30 text-indigo-400 rounded-xl font-bold transition-all pointer-events-none"
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Pacing Mode</label>
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
onClick={() => setPacingMode('self_paced')}
|
||||
className={`flex-1 p-4 rounded-2xl border-2 transition-all text-left ${pacingMode === 'self_paced' ? 'border-blue-500 bg-blue-500/10' : 'border-white/5 bg-white/5 hover:border-white/10'}`}
|
||||
>
|
||||
<div className="font-bold">Self-Paced</div>
|
||||
<div className="text-xs text-gray-500">Learners go at their own speed.</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPacingMode('instructor_led')}
|
||||
className={`flex-1 p-4 rounded-2xl border-2 transition-all text-left ${pacingMode === 'instructor_led' ? 'border-purple-500 bg-purple-500/10' : 'border-white/5 bg-white/5 hover:border-white/10'}`}
|
||||
>
|
||||
<div className="font-bold">Instructor-Led</div>
|
||||
<div className="text-xs text-gray-500">Cohort-based with specific dates.</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pacingMode === 'instructor_led' && (
|
||||
<div className="space-y-4 animate-in fade-in slide-in-from-top-2">
|
||||
<label className="block text-sm font-bold text-gray-300">Course Schedule</label>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs text-gray-500">Start Date</label>
|
||||
<div className="relative">
|
||||
<Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs text-gray-500">End Date</label>
|
||||
<div className="relative">
|
||||
<Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Course Pricing Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-blue-500/10 flex items-center justify-center text-blue-400">
|
||||
<span className="text-xl font-bold">$</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Pricing</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Price</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(parseFloat(e.target.value))}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-3 px-4 text-white focus:outline-none focus:border-blue-500 transition-colors"
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<div className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 font-bold">
|
||||
{currency}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">Set to 0 for a free course.</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-bold text-gray-300">Currency</label>
|
||||
<select
|
||||
value={currency}
|
||||
onChange={(e) => setCurrency(e.target.value)}
|
||||
className="w-full bg-black/30 border border-white/10 rounded-xl py-3 px-4 text-white focus:outline-none focus:border-blue-500 transition-colors appearance-none"
|
||||
>
|
||||
<Upload size={18} />
|
||||
{importing ? "Importing..." : "Upload JSON"}
|
||||
</button>
|
||||
<option value="USD">USD - US Dollar</option>
|
||||
<option value="CLP">CLP - Chilean Peso</option>
|
||||
<option value="ARS">ARS - Argentine Peso</option>
|
||||
<option value="BRL">BRL - Brazilian Real</option>
|
||||
<option value="MXN">MXN - Mexican Peso</option>
|
||||
<option value="COP">COP - Colombian Peso</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
{/* Certificate Template Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-400">
|
||||
<BookOpen size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Certificate Template</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<p className="text-gray-400">
|
||||
Design the HTML certificate that students will receive upon passing the course.
|
||||
Available variables: <code className="text-blue-400">{"{{student_name}}"}</code>, <code className="text-blue-400">{"{{course_title}}"}</code>, <code className="text-blue-400">{"{{date}}"}</code>, <code className="text-blue-400">{"{{score}}"}</code>.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-300">HTML Template</label>
|
||||
<textarea
|
||||
value={certificateTemplate}
|
||||
onChange={(e) => setCertificateTemplate(e.target.value)}
|
||||
className="w-full h-[400px] bg-black/30 border border-white/10 rounded-xl p-4 font-mono text-sm text-gray-300 focus:outline-none focus:border-blue-500 transition-colors resize-none"
|
||||
placeholder="Enter HTML code here..."
|
||||
/>
|
||||
<button
|
||||
onClick={() => setCertificateTemplate(DEFAULT_CERTIFICATE_TEMPLATE)}
|
||||
className="text-xs text-blue-400 hover:text-blue-300 underline"
|
||||
>
|
||||
Reset to Default Template
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-300">Live Preview</label>
|
||||
<div className="w-full h-[400px] bg-white rounded-xl overflow-hidden relative group">
|
||||
<iframe
|
||||
srcDoc={certificateTemplate
|
||||
.replace(/{{student_name}}/g, "Jane Doe")
|
||||
.replace(/{{course_title}}/g, course?.title || "Demo Course")
|
||||
.replace(/{{date}}/g, new Date().toLocaleDateString())
|
||||
.replace(/{{score}}/g, "95")
|
||||
}
|
||||
className="w-full h-full transform scale-75 origin-top-left w-[133%] h-[133%]"
|
||||
style={{ border: "none" }}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 pointer-events-none transition-colors" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{/* Course Portability Section */}
|
||||
<section className="bg-white/5 border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-12 h-12 rounded-2xl bg-amber-500/10 flex items-center justify-center text-amber-400">
|
||||
<Download size={24} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black">Course Portability</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-bold text-gray-300">Export Course</h3>
|
||||
<p className="text-xs text-gray-500">
|
||||
Download the entire course structure, modules, and lessons as a JSON file.
|
||||
You can use this to backup or move content between organizations.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleExport}
|
||||
disabled={exporting}
|
||||
className="flex items-center gap-2 px-6 py-3 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl font-bold transition-all active:scale-95 disabled:opacity-50"
|
||||
>
|
||||
<Download size={18} />
|
||||
{exporting ? "Exporting..." : "Download JSON"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-bold text-gray-300">Import Course</h3>
|
||||
<p className="text-xs text-gray-500">
|
||||
Upload a previously exported course JSON file. This will create a NEW course
|
||||
within the current organization based on that data.
|
||||
</p>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleImport}
|
||||
disabled={importing}
|
||||
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
|
||||
/>
|
||||
<button
|
||||
disabled={importing}
|
||||
className="flex items-center gap-2 px-6 py-3 bg-indigo-600/20 hover:bg-indigo-600/30 border border-indigo-500/30 text-indigo-400 rounded-xl font-bold transition-all pointer-events-none"
|
||||
>
|
||||
<Upload size={18} />
|
||||
{importing ? "Importing..." : "Upload JSON"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</CourseEditorLayout>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -503,6 +503,16 @@ export interface PeerReview {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface CourseInstructor {
|
||||
id: string;
|
||||
course_id: string;
|
||||
user_id: string;
|
||||
role: 'primary' | 'instructor' | 'assistant';
|
||||
created_at: string;
|
||||
email: string;
|
||||
full_name: string;
|
||||
}
|
||||
|
||||
const getToken = () => typeof window !== 'undefined' ? localStorage.getItem('studio_token') : null;
|
||||
const getSelectedOrgId = () => typeof window !== 'undefined' ? localStorage.getItem('studio_selected_org_id') : null;
|
||||
|
||||
@@ -552,6 +562,12 @@ export const cmsApi = {
|
||||
getCourseWithFullOutline: (id: string): Promise<Course> => apiFetch(`/courses/${id}/outline`),
|
||||
updateCourse: (id: string, payload: Partial<Course>): Promise<Course> => apiFetch(`/courses/${id}`, { method: 'PUT', body: JSON.stringify(payload) }),
|
||||
publishCourse: (id: string, targetOrganizationId?: string): Promise<void> => apiFetch(`/courses/${id}/publish`, { method: 'POST', body: JSON.stringify({ target_organization_id: targetOrganizationId }) }),
|
||||
getPreviewToken: (id: string): Promise<{ token: string }> => apiFetch(`/courses/${id}/preview-token`, { method: 'POST' }),
|
||||
|
||||
// Team Management
|
||||
getCourseTeam: (courseId: string): Promise<CourseInstructor[]> => apiFetch(`/courses/${courseId}/team`),
|
||||
addTeamMember: (courseId: string, email: string, role: string): Promise<CourseInstructor> => apiFetch(`/courses/${courseId}/team`, { method: 'POST', body: JSON.stringify({ email, role }) }),
|
||||
removeTeamMember: (courseId: string, userId: string): Promise<void> => apiFetch(`/courses/${courseId}/team/${userId}`, { method: 'DELETE' }),
|
||||
|
||||
// Modules & Lessons
|
||||
createModule: (course_id: string, title: string, position: number): Promise<Module> => apiFetch('/modules', { method: 'POST', body: JSON.stringify({ course_id, title, position }) }),
|
||||
|
||||
Reference in New Issue
Block a user