Refactor code structure for improved readability and maintainability

This commit is contained in:
2026-03-31 14:39:04 -03:00
parent 8b792e1d44
commit 0bea4173f5
18 changed files with 517 additions and 192 deletions
+5 -2
View File
@@ -62,8 +62,8 @@ EXTERNAL_ID_TIPO_NOTA=1
MP_ACCESS_TOKEN=
MP_PUBLIC_KEY=
MP_WEBHOOK_SECRET=
MP_BACK_URL_SUCCESS=https://learning.norteamericano.com/payments/success
MP_BACK_URL_FAILURE=https://learning.norteamericano.com/payments/failure
MP_BACK_URL_SUCCESS=https://${NEXT_PUBLIC_LEARNING_DOMAIN}/payments/success
MP_BACK_URL_FAILURE=https://${NEXT_PUBLIC_LEARNING_DOMAIN}/payments/failure
MP_NOTIFICATION_URL=
# ----------------------------------------
@@ -85,6 +85,9 @@ LETSENCRYPT_STAGING=true
# ----------------------------------------
# Frontend URLs (para producción con SSL)
# Dominios configurables - cambiar aquí para mover a otro dominio
# ----------------------------------------
NEXT_PUBLIC_STUDIO_DOMAIN=studio.norteamericano.com
NEXT_PUBLIC_LEARNING_DOMAIN=learning.norteamericano.com
NEXT_PUBLIC_CMS_API_URL=https://studio.norteamericano.com
NEXT_PUBLIC_LMS_API_URL=https://learning.norteamericano.com
+19 -11
View File
@@ -25,6 +25,14 @@ LETSENCRYPT_STAGING="true"
GIT_REPO="https://github.com/Nurfog/learningccb.git"
# ============================================================================
# Cargar dominios desde .env si existen, con valores por defecto
if [ -f ".env" ]; then
_STUDIO_DOMAIN=$(grep '^NEXT_PUBLIC_STUDIO_DOMAIN=' .env | cut -d'=' -f2)
_LEARNING_DOMAIN=$(grep '^NEXT_PUBLIC_LEARNING_DOMAIN=' .env | cut -d'=' -f2)
fi
STUDIO_DOMAIN="${_STUDIO_DOMAIN:-studio.norteamericano.com}"
LEARNING_DOMAIN="${_LEARNING_DOMAIN:-learning.norteamericano.com}"
# Si PEM_PATH es relativo, convertirlo a absoluto
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ "$PEM_PATH" != /* ]]; then
@@ -409,11 +417,11 @@ fi
# Configurar URLs de la API para el frontend
echo " Configurando URLs de la API para el frontend..."
if [ "$PROTOCOL" = "https" ]; then
CMS_URL="https://studio.norteamericano.com"
LMS_URL="https://learning.norteamericano.com"
CMS_URL="https://$STUDIO_DOMAIN"
LMS_URL="https://$LEARNING_DOMAIN"
else
CMS_URL="http://studio.norteamericano.com"
LMS_URL="http://learning.norteamericano.com"
CMS_URL="http://$STUDIO_DOMAIN"
LMS_URL="http://$LEARNING_DOMAIN"
fi
# Remover valores existentes
@@ -462,7 +470,7 @@ else
echo " ⚠️ Faltan argumentos de build, agregando..."
# Agregar argumentos si faltan
if ! grep -q "NEXT_PUBLIC_LMS_API_URL:" docker-compose.yml; then
sed -i '/NEXT_PUBLIC_CMS_API_URL:/a\ NEXT_PUBLIC_LMS_API_URL: http://learning.norteamericano.com' docker-compose.yml
sed -i "/NEXT_PUBLIC_CMS_API_URL:/a\\ NEXT_PUBLIC_LMS_API_URL: http://$LEARNING_DOMAIN" docker-compose.yml
fi
fi
echo ""
@@ -645,8 +653,8 @@ if [ "\$PROTOCOL" = "https" ] || [ "\$PRESERVE_SSL_CERTS" = "true" ]; then
fi
}
repair_ssl_for_domain "studio.norteamericano.com"
repair_ssl_for_domain "learning.norteamericano.com"
repair_ssl_for_domain "$STUDIO_DOMAIN"
repair_ssl_for_domain "$LEARNING_DOMAIN"
if \$DOCKER_CMD exec nginx-proxy nginx -t >/tmp/nginx_ssl_check.log 2>&1; then
\$DOCKER_CMD exec nginx-proxy nginx -s reload >/dev/null 2>&1 || true
@@ -788,8 +796,8 @@ echo " CREDENCIALES DE ACCESO"
echo "========================================"
echo ""
echo "URLs de acceso:"
echo " Studio - CMS: $PROTOCOL://studio.norteamericano.com"
echo " Experience - LMS: $PROTOCOL://learning.norteamericano.com"
echo " Studio - CMS: $PROTOCOL://$STUDIO_DOMAIN"
echo " Experience - LMS: $PROTOCOL://$LEARNING_DOMAIN"
echo ""
echo "Usuario Administrador:"
echo " Email: $ADMIN_EMAIL"
@@ -887,8 +895,8 @@ if [ $SCRIPT_EXIT -eq 0 ]; then
echo ""
echo "Accede a tu plataforma:"
echo " Studio - CMS: $PROTOCOL://studio.norteamericano.com"
echo " Experience - LMS: $PROTOCOL://learning.norteamericano.com"
echo " Studio - CMS: $PROTOCOL://$STUDIO_DOMAIN"
echo " Experience - LMS: $PROTOCOL://$LEARNING_DOMAIN"
echo ""
echo "Conectate para administrar:"
echo " ssh -i \"$PEM_PATH\" $REMOTE_USER@$REMOTE_HOST"
+12 -6
View File
@@ -19,8 +19,8 @@ services:
- vhost:/etc/nginx/vhost.d
- html:/usr/share/nginx/html
- ./nginx/proxy.conf:/etc/nginx/conf.d/proxy.conf:ro
- ./nginx/studio.conf:/etc/nginx/vhost.d/studio.norteamericano.com:ro
- ./nginx/learning.conf:/etc/nginx/vhost.d/learning.norteamericano.com:ro
- ./nginx/studio.conf:/etc/nginx/vhost.d/${NEXT_PUBLIC_STUDIO_DOMAIN}:ro
- ./nginx/learning.conf:/etc/nginx/vhost.d/${NEXT_PUBLIC_LEARNING_DOMAIN}:ro
restart: always
networks:
- openccb-network
@@ -75,15 +75,19 @@ services:
args:
NEXT_PUBLIC_CMS_API_URL: ${NEXT_PUBLIC_CMS_API_URL}
NEXT_PUBLIC_LMS_API_URL: ${NEXT_PUBLIC_LMS_API_URL}
NEXT_PUBLIC_STUDIO_DOMAIN: ${NEXT_PUBLIC_STUDIO_DOMAIN}
NEXT_PUBLIC_LEARNING_DOMAIN: ${NEXT_PUBLIC_LEARNING_DOMAIN}
container_name: openccb-studio
environment:
- VIRTUAL_HOST=studio.norteamericano.com
- VIRTUAL_HOST=${NEXT_PUBLIC_STUDIO_DOMAIN}
- VIRTUAL_PORT=3000
- LETSENCRYPT_HOST=studio.norteamericano.com
- LETSENCRYPT_HOST=${NEXT_PUBLIC_STUDIO_DOMAIN}
- HTTPS_METHOD=noredirect
- HSTS=off
- HOSTNAME=0.0.0.0
- DATABASE_URL=${CMS_DATABASE_URL}
- MYSQL_DATABASE_URL=${MYSQL_DATABASE_URL}
- SAM_DIAGNOSTICO_DATABASE_URL=${SAM_DIAGNOSTICO_DATABASE_URL}
- LMS_INTERNAL_URL=http://experience:3002
- NEXT_PUBLIC_LMS_API_URL=${NEXT_PUBLIC_LMS_API_URL}
volumes:
@@ -109,11 +113,13 @@ services:
args:
NEXT_PUBLIC_LMS_API_URL: ${NEXT_PUBLIC_LMS_API_URL}
NEXT_PUBLIC_CMS_API_URL: ${NEXT_PUBLIC_CMS_API_URL}
NEXT_PUBLIC_STUDIO_DOMAIN: ${NEXT_PUBLIC_STUDIO_DOMAIN}
NEXT_PUBLIC_LEARNING_DOMAIN: ${NEXT_PUBLIC_LEARNING_DOMAIN}
container_name: openccb-experience
environment:
- VIRTUAL_HOST=learning.norteamericano.com
- VIRTUAL_HOST=${NEXT_PUBLIC_LEARNING_DOMAIN}
- VIRTUAL_PORT=3003
- LETSENCRYPT_HOST=learning.norteamericano.com
- LETSENCRYPT_HOST=${NEXT_PUBLIC_LEARNING_DOMAIN}
- HTTPS_METHOD=noredirect
- HSTS=off
- HOSTNAME=0.0.0.0
@@ -1491,3 +1491,229 @@ async fn generate_course_structure<'a>(
Ok((total_modules, total_lessons))
}
// ==================== Import from SAM Diagnostico ====================
/// Row retornada por GROUP BY sobre las tablas de SAM_diagnostico
#[derive(Debug, sqlx::FromRow)]
struct SamDiagnosticoQuestion {
pub id_test: i32,
pub id_curso: i32,
pub id_pregunta: i32,
pub pregunta_nombre: Option<String>,
pub tipo_pregunta: Option<String>,
/// Opciones separadas por '|||' (GROUP_CONCAT)
pub opciones: Option<String>,
/// Texto de la respuesta correcta (valorRespuesta = 1)
pub respuesta_correcta: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub struct ImportSamDiagnosticoPayload {
/// "adultos", "kids", "teens" o null para importar las tres audiencias
pub audience: Option<String>,
/// Filtra por idTest específico (opcional)
pub test_id: Option<i32>,
/// Filtra por idCurso específico (opcional)
pub curso_id: Option<i32>,
}
/// POST /api/question-bank/import-sam-diagnostico
/// Importa preguntas desde las tablas SAM_diagnostico (preguntasadultos,
/// preguntaskid, preguntasteens) al banco de preguntas de PostgreSQL.
pub async fn import_from_sam_diagnostico(
Org(org_ctx): Org,
claims: Claims,
State(pool): State<PgPool>,
Json(payload): Json<ImportSamDiagnosticoPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
use serde_json::json;
let sam_diag_url = std::env::var("SAM_DIAGNOSTICO_DATABASE_URL")
.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"SAM_DIAGNOSTICO_DATABASE_URL not configured".to_string(),
)
})?;
let mysql_pool = sqlx::MySqlPool::connect(&sam_diag_url)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to connect to SAM_diagnostico: {}", e),
)
})?;
// Determinar qué tablas procesar según la audiencia solicitada
let tables: Vec<(&str, &str)> = match payload.audience.as_deref() {
Some("adultos") => vec![("adultos", "preguntasadultos")],
Some("kids") => vec![("kids", "preguntaskid")],
Some("teens") => vec![("teens", "preguntasteens")],
_ => vec![
("adultos", "preguntasadultos"),
("kids", "preguntaskid"),
("teens", "preguntasteens"),
],
};
let mut total_imported: i64 = 0;
let mut total_skipped: i64 = 0;
let mut errors: Vec<String> = Vec::new();
for (audience_label, table_name) in &tables {
// GROUP_CONCAT agrupa todas las opciones de cada pregunta en una sola fila.
// El separador '|||' no puede aparecer en los textos de respuesta normales.
let base_query = format!(
r#"
SELECT
idTest AS id_test,
idCurso AS id_curso,
idPregunta AS id_pregunta,
MAX(preguntaNombre) AS pregunta_nombre,
MAX(tipoPregunta) AS tipo_pregunta,
GROUP_CONCAT(
respuestaNombre
ORDER BY idOpcion
SEPARATOR '|||'
) AS opciones,
MAX(CASE WHEN valorRespuesta = 1 THEN respuestaNombre ELSE NULL END)
AS respuesta_correcta
FROM {}
WHERE 1=1
{}
{}
GROUP BY idTest, idCurso, idPregunta
ORDER BY idTest, idCurso, idPregunta
"#,
table_name,
if payload.test_id.is_some() { "AND idTest = ?" } else { "" },
if payload.curso_id.is_some() { "AND idCurso = ?" } else { "" },
);
// Bind parámetros opcionales de forma dinámica
let rows: Vec<SamDiagnosticoQuestion> = {
let mut q = sqlx::query_as::<_, SamDiagnosticoQuestion>(&base_query);
if let Some(tid) = payload.test_id { q = q.bind(tid); }
if let Some(cid) = payload.curso_id { q = q.bind(cid); }
q.fetch_all(&mysql_pool)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to fetch from {}: {}", table_name, e),
)
})?
};
tracing::info!(
"SAM_diagnostico {}: {} preguntas encontradas",
table_name, rows.len()
);
for question in rows {
let question_text = match &question.pregunta_nombre {
Some(t) if !t.trim().is_empty() => t.clone(),
_ => continue, // Saltar preguntas sin texto
};
// Clave única para detectar duplicados
let sam_id = format!(
"{}-{}-{}-{}",
audience_label, question.id_test, question.id_curso, question.id_pregunta
);
let exists: (bool,) = sqlx::query_as(
"SELECT EXISTS(SELECT 1 FROM question_bank \
WHERE source_metadata->>'sam_id' = $1 AND organization_id = $2)"
)
.bind(&sam_id)
.bind(org_ctx.id)
.fetch_one(&pool)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to check duplicate: {}", e),
)
})?;
if exists.0 {
total_skipped += 1;
continue;
}
// Convertir GROUP_CONCAT → Vec<String>
let options_vec: Vec<String> = question
.opciones
.as_deref()
.unwrap_or("")
.split("|||")
.map(|s| s.to_string())
.filter(|s| !s.is_empty())
.collect();
let options_json = if options_vec.is_empty() {
serde_json::Value::Null
} else {
json!(options_vec)
};
let correct_json = question
.respuesta_correcta
.as_ref()
.map(|a| json!(a))
.unwrap_or(serde_json::Value::Null);
let source_metadata = json!({
"sam_id": sam_id,
"audience": audience_label,
"tabla": table_name,
"idTest": question.id_test,
"idCurso": question.id_curso,
"idPregunta": question.id_pregunta,
"imported_at": chrono::Utc::now().to_rfc3339(),
});
match sqlx::query(
r#"
INSERT INTO question_bank (
organization_id, created_by, question_text, question_type,
options, correct_answer, source, source_metadata,
audio_status, is_active
)
VALUES ($1, $2, $3, 'multiple_choice', $4, $5, 'sam-diagnostico', $6, 'pending', true)
"#
)
.bind(org_ctx.id)
.bind(claims.sub)
.bind(&question_text)
.bind(&options_json)
.bind(&correct_json)
.bind(&source_metadata)
.execute(&pool)
.await
{
Ok(_) => total_imported += 1,
Err(e) => errors.push(format!(
"Error importando pregunta {} ({}): {}",
question.id_pregunta, table_name, e
)),
}
}
}
mysql_pool.close().await;
tracing::info!(
"SAM_diagnostico import done: imported={} skipped={} errors={}",
total_imported, total_skipped, errors.len()
);
Ok(Json(json!({
"imported": total_imported,
"skipped": total_skipped,
"errors": errors,
})))
}
+4
View File
@@ -403,6 +403,10 @@ async fn main() {
"/question-bank/import-course-mysql",
post(handlers_question_bank::import_course_from_mysql),
)
.route(
"/question-bank/import-sam-diagnostico",
post(handlers_question_bank::import_from_sam_diagnostico),
)
.route(
"/question-bank/ai-generate",
post(handlers_question_bank::ai_generate_question),
+6 -4
View File
@@ -1,3 +1,5 @@
const LEARNING_DOMAIN = process.env.NEXT_PUBLIC_LEARNING_DOMAIN || 'learning.norteamericano.com';
const getApiBaseUrl = (defaultPort: string, envVar?: string) => {
if (envVar && envVar.trim() !== '') {
return envVar;
@@ -11,14 +13,14 @@ const getApiBaseUrl = (defaultPort: string, envVar?: string) => {
};
export const getLmsApiUrl = () => {
if (typeof window !== 'undefined' && window.location.hostname === 'learning.norteamericano.com') {
return `${window.location.protocol}//learning.norteamericano.com/lms-api`;
if (typeof window !== 'undefined' && window.location.hostname === LEARNING_DOMAIN) {
return `${window.location.protocol}//${LEARNING_DOMAIN}/lms-api`;
}
return getApiBaseUrl("3002", process.env.NEXT_PUBLIC_LMS_API_URL);
};
export const getCmsApiUrl = () => {
if (typeof window !== 'undefined' && window.location.hostname === 'learning.norteamericano.com') {
return `${window.location.protocol}//learning.norteamericano.com/cms-api`;
if (typeof window !== 'undefined' && window.location.hostname === LEARNING_DOMAIN) {
return `${window.location.protocol}//${LEARNING_DOMAIN}/cms-api`;
}
return getApiBaseUrl("3001", process.env.NEXT_PUBLIC_CMS_API_URL);
};
+1 -1
View File
@@ -19,7 +19,7 @@ const nextConfig = {
},
{
protocol: 'https',
hostname: 'studio.norteamericano.com',
hostname: process.env.NEXT_PUBLIC_STUDIO_DOMAIN || 'studio.norteamericano.com',
pathname: '/assets/**',
},
],
+1 -1
View File
@@ -223,7 +223,7 @@ export default function StudioLoginPage() {
<div className="mt-6 pt-6 border-t border-gray-200 dark:border-white/10 text-center transition-colors">
<p className="text-sm text-gray-500 dark:text-gray-400">
Are you a student?{" "}
<a href="https://learning.norteamericano.com/auth/login" className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-bold transition-colors">
<a href={`https://${process.env.NEXT_PUBLIC_LEARNING_DOMAIN || 'learning.norteamericano.com'}/auth/login`} className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-bold transition-colors">
Go to Student Portal
</a>
</p>
@@ -197,7 +197,7 @@ export default function LessonEditor({ params }: { params: { id: string; lessonI
}
const updated = await cmsApi.updateLesson(lesson.id, {
metadata: { ...lesson.metadata },
metadata: lesson.metadata ?? { blocks: [] },
content_blocks: blocks,
content_url,
content_type, // Sync type to ensure backend triggers transcription
@@ -348,11 +348,16 @@ export default function LessonEditor({ params }: { params: { id: string; lessonI
};
setBlocks([...blocks, newBlock]);
} else {
const newBlocks = await cmsApi.generateQuiz(lesson.id, {
const generatedQuiz = await cmsApi.generateQuiz(lesson.id, {
prompt_hint: aiQuizContext,
quiz_type: aiQuizType
});
setBlocks([...blocks, ...newBlocks]);
const newBlock: Block = {
id: Math.random().toString(36).substr(2, 9),
type: 'quiz',
quiz_data: { questions: generatedQuiz.questions }
};
setBlocks([...blocks, newBlock]);
}
setAiQuizContext("");
} catch (err) {
+15 -18
View File
@@ -1,28 +1,25 @@
'use client';
import React from 'react';
import React, { useState } from 'react';
import PageLayout from '@/components/PageLayout';
import { AlertTriangle } from 'lucide-react';
import TestTemplateManager from '@/components/TestTemplates/TestTemplateManager';
import TestTemplateForm from '@/components/TestTemplates/TestTemplateForm';
export default function TestTemplatesPage() {
const [view, setView] = useState<'list' | 'create'>('list');
return (
<PageLayout title="Plantillas de Pruebas">
<div className="flex flex-col items-center justify-center p-8">
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-6 max-w-2xl">
<div className="flex items-center gap-3 mb-4">
<AlertTriangle className="w-8 h-8 text-yellow-600" />
<h2 className="text-xl font-semibold text-yellow-800">
Funcionalidad Temporalmente Desactivada
</h2>
</div>
<p className="text-yellow-700 mb-4">
Las plantillas de pruebas están temporalmente desactivadas mientras se realizan mejoras en el sistema.
</p>
<p className="text-yellow-600 text-sm">
Esta funcionalidad estará disponible próximamente.
</p>
</div>
</div>
{view === 'list' ? (
<TestTemplateManager
onCreateTemplate={() => setView('create')}
/>
) : (
<TestTemplateForm
onSuccess={() => setView('list')}
onCancel={() => setView('list')}
/>
)}
</PageLayout>
);
}
@@ -114,7 +114,7 @@ export default function QuestionBankCard({ question, onEdit, onDelete }: Questio
{/* Question Text */}
<p className="text-gray-900 dark:text-white font-medium mb-3 line-clamp-3">
{question.question_text}
{String(question.question_text)}
</p>
{/* Audio Player */}
@@ -33,6 +33,10 @@ export default function QuestionBankEditor({ question, onSuccess, onCancel }: Qu
const [saving, setSaving] = useState(false);
const [generatingAI, setGeneratingAI] = useState(false);
const normalizedOptions = Array.isArray(formData.options)
? (formData.options as string[])
: [];
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -109,7 +113,7 @@ export default function QuestionBankEditor({ question, onSuccess, onCancel }: Qu
};
const handleAddOption = () => {
const currentOptions = formData.options || [];
const currentOptions = normalizedOptions;
setFormData({
...formData,
options: [...currentOptions, `Opción ${currentOptions.length + 1}`],
@@ -117,7 +121,7 @@ export default function QuestionBankEditor({ question, onSuccess, onCancel }: Qu
};
const handleRemoveOption = (index: number) => {
const newOptions = (formData.options || []).filter((_: any, i: number) => i !== index);
const newOptions = normalizedOptions.filter((_, i) => i !== index);
setFormData({ ...formData, options: newOptions });
// Adjust correct answer if needed
@@ -291,7 +295,7 @@ export default function QuestionBankEditor({ question, onSuccess, onCancel }: Qu
</button>
</div>
{formData.options?.map((option: any, idx: number) => (
{normalizedOptions.map((option: string, idx: number) => (
<div key={idx} className="flex items-center gap-2">
<input
type="radio"
@@ -304,7 +308,7 @@ export default function QuestionBankEditor({ question, onSuccess, onCancel }: Qu
type="text"
value={option}
onChange={(e) => {
const newOptions = [...(formData.options || [])];
const newOptions = [...normalizedOptions];
newOptions[idx] = e.target.value;
setFormData({ ...formData, options: newOptions });
}}
@@ -99,12 +99,12 @@ export default function TestTemplateForm({ onSuccess, onCancel }: TestTemplateFo
}, [selectedPlanId]);
// Handle course selection - store mysql_course_id (preferred approach)
const handleCourseSelect = (courseId: number) => {
const handleCourseSelect = (courseId: number | '') => {
setSelectedCourseId(courseId);
// Store the MySQL course ID directly - level/course_type can be derived from mysql_courses table
setFormData({
...formData,
mysql_course_id: courseId,
mysql_course_id: courseId === '' ? undefined : courseId,
});
};
@@ -299,6 +299,13 @@ export default function TestTemplateForm({ onSuccess, onCancel }: TestTemplateFo
));
};
const handleRemoveQuestion = (questionId: string) => {
setQuestions(questions.filter(q => q.id !== questionId));
if (expandedQuestion === questionId) {
setExpandedQuestion(null);
}
};
const getQuestionTypeLabel = (type: QuestionType) => {
const labels: Record<QuestionType, string> = {
'multiple-choice': 'Opción Múltiple',
@@ -1,8 +1,17 @@
'use client';
import React, { useState, useEffect } from 'react';
import { cmsApi, TestTemplate, TestTemplateFilters, CourseLevel, CourseType, TestType, Course } from '@/lib/api';
import { Plus, Search, Filter, Edit2, Trash2, Eye, Copy, BookOpen, Clock, Target, Tag, ExternalLink, X } from 'lucide-react';
import React, { useEffect, useMemo, useState } from 'react';
import {
cmsApi,
questionBankApi,
TestTemplate,
TestTemplateFilters,
TestType,
Course,
MySqlPlan,
MySqlCourse,
} from '@/lib/api';
import { Plus, Search, Filter, Edit2, Trash2, Eye, Copy, BookOpen, Clock, Target, Tag, X } from 'lucide-react';
interface TestTemplateManagerProps {
onSelectTemplate?: (template: TestTemplate) => void;
@@ -12,16 +21,37 @@ interface TestTemplateManagerProps {
export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate }: TestTemplateManagerProps) {
const [templates, setTemplates] = useState<TestTemplate[]>([]);
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState<TestTemplateFilters>({});
const [showFilters, setShowFilters] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
const [filterPlans, setFilterPlans] = useState<MySqlPlan[]>([]);
const [filterCourses, setFilterCourses] = useState<MySqlCourse[]>([]);
const [filterPlanId, setFilterPlanId] = useState<number | ''>('');
const [filterCourseId, setFilterCourseId] = useState<number | ''>('');
const [showApplyModal, setShowApplyModal] = useState(false);
const [selectedTemplate, setSelectedTemplate] = useState<TestTemplate | null>(null);
const [courses, setCourses] = useState<Course[]>([]);
const [applyPlans, setApplyPlans] = useState<MySqlPlan[]>([]);
const [applyCourses, setApplyCourses] = useState<MySqlCourse[]>([]);
const [applyPlanId, setApplyPlanId] = useState<number | ''>('');
const [applyCourseId, setApplyCourseId] = useState<number | ''>('');
const [selectedCourse, setSelectedCourse] = useState<string>('');
const [selectedLesson, setSelectedLesson] = useState<string>('');
const [applying, setApplying] = useState(false);
const resetApplyState = () => {
setSelectedTemplate(null);
setApplyPlanId('');
setApplyCourseId('');
setSelectedCourse('');
setSelectedLesson('');
};
const loadTemplates = async () => {
try {
setLoading(true);
@@ -38,9 +68,44 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
loadTemplates();
}, [filters]);
useEffect(() => {
questionBankApi.getMySQLPlans().then(setFilterPlans).catch(() => {});
questionBankApi.getMySQLPlans().then(setApplyPlans).catch(() => {});
}, []);
useEffect(() => {
if (!filterPlanId) {
setFilterCourses([]);
setFilterCourseId('');
setFilters((f) => ({ ...f, mysql_course_id: undefined }));
return;
}
questionBankApi.getMySQLCoursesByPlan(filterPlanId).then(setFilterCourses).catch(() => {});
}, [filterPlanId]);
useEffect(() => {
if (!applyPlanId) {
setApplyCourses([]);
setApplyCourseId('');
return;
}
questionBankApi.getMySQLCoursesByPlan(applyPlanId).then(setApplyCourses).catch(() => {});
}, [applyPlanId]);
const filteredTemplates = useMemo(() => {
if (!searchTerm.trim()) return templates;
const q = searchTerm.toLowerCase();
return templates.filter((t) => {
const inName = t.name?.toLowerCase().includes(q);
const inDesc = t.description?.toLowerCase().includes(q);
const inTags = (t.tags || []).some((tag) => tag.toLowerCase().includes(q));
return Boolean(inName || inDesc || inTags);
});
}, [templates, searchTerm]);
const handleDelete = async (id: string) => {
if (!confirm('¿Estás seguro de que deseas eliminar esta plantilla?')) return;
try {
await cmsApi.deleteTestTemplate(id);
await loadTemplates();
@@ -53,16 +118,14 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
const handleApplyTemplate = async (template: TestTemplate) => {
setSelectedTemplate(template);
setShowApplyModal(true);
loadCourses();
};
setApplyPlanId('');
setApplyCourseId('');
setSelectedCourse('');
setSelectedLesson('');
const loadCourses = async () => {
try {
const data = await cmsApi.getCourses();
setCourses(data);
} catch (error) {
console.error('Failed to load courses:', error);
}
cmsApi.getCourses()
.then(setCourses)
.catch((e) => console.error('Failed to load courses:', e));
};
const handleApplyToLesson = async () => {
@@ -76,9 +139,7 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
await cmsApi.applyTemplateToLesson(selectedTemplate.id, selectedLesson);
alert('Plantilla aplicada exitosamente a la lección');
setShowApplyModal(false);
setSelectedTemplate(null);
setSelectedCourse('');
setSelectedLesson('');
resetApplyState();
} catch (error) {
console.error('Failed to apply template:', error);
alert('Error al aplicar la plantilla');
@@ -87,25 +148,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
}
};
const getLevelLabel = (level: CourseLevel) => {
const labels: Record<CourseLevel, string> = {
beginner: 'Beginner',
beginner_1: 'Beginner 1',
beginner_2: 'Beginner 2',
intermediate: 'Intermediate',
intermediate_1: 'Intermediate 1',
intermediate_2: 'Intermediate 2',
advanced: 'Advanced',
advanced_1: 'Advanced 1',
advanced_2: 'Advanced 2',
};
return labels[level] || level;
};
const getCourseTypeLabel = (type: CourseType) => {
return type === 'intensive' ? 'Intensivo' : 'Regular';
};
const getTestTypeLabel = (type: TestType) => {
const labels: Record<TestType, string> = {
CA: 'Evaluación Continua',
@@ -117,13 +159,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
return labels[type] || type;
};
const getLevelColor = (level: CourseLevel) => {
if (level.includes('beginner')) return 'bg-green-100 text-green-800';
if (level.includes('intermediate')) return 'bg-yellow-100 text-yellow-800';
if (level.includes('advanced')) return 'bg-red-100 text-red-800';
return 'bg-gray-100 text-gray-800';
};
const getTestTypeColor = (type: TestType) => {
if (type === 'CA') return 'bg-blue-100 text-blue-800';
if (type.includes('MWT') || type.includes('MOT')) return 'bg-purple-100 text-purple-800';
@@ -133,12 +168,11 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
return (
<div className="p-6">
{/* Header */}
<div className="mb-6 flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Plantillas de Pruebas</h1>
<p className="text-sm text-gray-600 mt-1">
Gestiona plantillas de evaluaciones por nivel y tipo de curso
Gestiona plantillas y vincúlalas a una lección específica de un curso
</p>
</div>
<button
@@ -150,7 +184,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</button>
</div>
{/* Search and Filters */}
<div className="mb-6 flex gap-3">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
@@ -173,45 +206,51 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</button>
</div>
{/* Filter Panel */}
{showFilters && (
<div className="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200 grid grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Nivel</label>
<label className="block text-sm font-medium text-gray-700 mb-1">Programa de Estudios</label>
<select
value={filters.level || ''}
onChange={(e) => setFilters({ ...filters, level: e.target.value as CourseLevel || undefined })}
value={filterPlanId}
onChange={(e) => {
const id = e.target.value ? Number(e.target.value) : '';
setFilterPlanId(id);
setFilterCourseId('');
setFilters((f) => ({ ...f, mysql_course_id: undefined }));
}}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Todos los niveles</option>
<option value="beginner">Beginner</option>
<option value="beginner_1">Beginner 1</option>
<option value="beginner_2">Beginner 2</option>
<option value="intermediate">Intermediate</option>
<option value="intermediate_1">Intermediate 1</option>
<option value="intermediate_2">Intermediate 2</option>
<option value="advanced">Advanced</option>
<option value="advanced_1">Advanced 1</option>
<option value="advanced_2">Advanced 2</option>
<option value="">Todos los programas</option>
{filterPlans.map((p) => (
<option key={p.idPlanDeEstudios} value={p.idPlanDeEstudios}>{p.NombrePlan}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Tipo de Curso</label>
<label className="block text-sm font-medium text-gray-700 mb-1">Curso</label>
<select
value={filters.course_type || ''}
onChange={(e) => setFilters({ ...filters, course_type: e.target.value as CourseType || undefined })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
value={filterCourseId}
disabled={!filterPlanId}
onChange={(e) => {
const id = e.target.value ? Number(e.target.value) : '';
setFilterCourseId(id);
setFilters((f) => ({ ...f, mysql_course_id: id || undefined }));
}}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
>
<option value="">Todos los tipos</option>
<option value="intensive">Intensivo</option>
<option value="regular">Regular</option>
<option value="">Todos los cursos</option>
{filterCourses.map((c) => (
<option key={c.idCursos} value={c.idCursos}>{c.NombreCurso}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Tipo de Prueba</label>
<select
value={filters.test_type || ''}
onChange={(e) => setFilters({ ...filters, test_type: e.target.value as TestType || undefined })}
onChange={(e) => setFilters({ ...filters, test_type: (e.target.value as TestType) || undefined })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Todos los tipos</option>
@@ -225,13 +264,12 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
)}
{/* Templates Grid */}
{loading ? (
<div className="text-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto" />
<p className="mt-4 text-gray-600">Cargando plantillas...</p>
</div>
) : templates.length === 0 ? (
) : filteredTemplates.length === 0 ? (
<div className="text-center py-12 bg-gray-50 rounded-lg">
<BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900">No hay plantillas</h3>
@@ -239,17 +277,16 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{templates.map((template) => (
{filteredTemplates.map((template) => (
<div
key={template.id}
className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-lg transition-shadow"
>
{/* Header */}
<div className="flex items-start justify-between mb-3">
<h3 className="font-semibold text-gray-900 flex-1">{template.name}</h3>
<div className="flex items-center gap-1">
<button
onClick={() => alert(`Implementar: Ver plantilla ${template.id}`)}
onClick={() => onSelectTemplate?.(template)}
className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
title="Ver detalles"
>
@@ -272,25 +309,21 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
</div>
{/* Description */}
{template.description && (
<p className="text-sm text-gray-600 mb-3 line-clamp-2">{template.description}</p>
)}
{/* Badges */}
<div className="flex flex-wrap gap-2 mb-3">
<span className={`px-2 py-1 rounded text-xs font-medium ${getLevelColor(template.level)}`}>
{getLevelLabel(template.level)}
</span>
<span className="px-2 py-1 rounded text-xs font-medium bg-gray-100 text-gray-800">
{getCourseTypeLabel(template.course_type)}
</span>
<span className={`px-2 py-1 rounded text-xs font-medium ${getTestTypeColor(template.test_type)}`}>
{getTestTypeLabel(template.test_type)}
</span>
{template.mysql_course_id && (
<span className="px-2 py-1 rounded text-xs font-medium bg-indigo-100 text-indigo-800">
Curso SAM #{template.mysql_course_id}
</span>
)}
</div>
{/* Metadata */}
<div className="space-y-2 mb-3">
<div className="flex items-center gap-2 text-sm text-gray-600">
<Clock className="w-4 h-4" />
@@ -306,7 +339,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
</div>
{/* Tags */}
{template.tags && template.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-3">
{template.tags.map((tag, idx) => (
@@ -317,11 +349,8 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
)}
{/* Usage Stats */}
<div className="flex items-center justify-between pt-3 border-t border-gray-200">
<span className="text-xs text-gray-500">
Usos: {template.usage_count}
</span>
<span className="text-xs text-gray-500">Usos: {template.usage_count}</span>
<button
onClick={() => handleApplyTemplate(template)}
className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors"
@@ -335,7 +364,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
)}
{/* Apply Template Modal */}
{showApplyModal && selectedTemplate && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
@@ -347,7 +375,7 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
<button
onClick={() => {
setShowApplyModal(false);
setSelectedTemplate(null);
resetApplyState();
}}
className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
>
@@ -356,7 +384,6 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
<div className="p-6 space-y-4">
{/* Template Info */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h4 className="font-semibold text-blue-900 mb-2">Información de la Plantilla</h4>
<div className="grid grid-cols-2 gap-3 text-sm">
@@ -377,40 +404,69 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
<span className="ml-2 font-medium">{selectedTemplate.passing_score}%</span>
</div>
</div>
<div className="mt-3 text-xs text-blue-700">
<p> Esta plantilla tiene <strong>1 solo intento</strong> por alumno.</p>
<p>📝 Los alumnos podrán ver sus respuestas permanentemente.</p>
</div>
</div>
{/* Select Course */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Curso
</label>
<label className="block text-sm font-medium text-gray-700 mb-1">1. Programa de Estudios</label>
<select
value={selectedCourse}
value={applyPlanId}
onChange={(e) => {
setSelectedCourse(e.target.value);
setApplyPlanId(e.target.value ? Number(e.target.value) : '');
setApplyCourseId('');
setSelectedCourse('');
setSelectedLesson('');
}}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Selecciona un curso...</option>
{courses.map((course) => (
<option key={course.id} value={course.id}>
{course.title}
</option>
<option value="">Selecciona un programa...</option>
{applyPlans.map((p) => (
<option key={p.idPlanDeEstudios} value={p.idPlanDeEstudios}>{p.NombrePlan}</option>
))}
</select>
</div>
{/* Select Lesson */}
{applyPlanId && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">2. Curso</label>
<select
value={applyCourseId}
onChange={(e) => {
setApplyCourseId(e.target.value ? Number(e.target.value) : '');
setSelectedCourse('');
setSelectedLesson('');
}}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Selecciona un curso...</option>
{applyCourses.map((c) => (
<option key={c.idCursos} value={c.idCursos}>{c.NombreCurso}</option>
))}
</select>
</div>
)}
{applyCourseId && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">3. Curso en la Plataforma</label>
<select
value={selectedCourse}
onChange={(e) => {
setSelectedCourse(e.target.value);
setSelectedLesson('');
}}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Selecciona el curso destino...</option>
{courses.map((course) => (
<option key={course.id} value={course.id}>{course.title}</option>
))}
</select>
</div>
)}
{selectedCourse && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Lección (debe ser de tipo "Quiz" o estar vacía)
</label>
<label className="block text-sm font-medium text-gray-700 mb-1">4. Lección</label>
<LessonSelector
courseId={selectedCourse}
selectedLesson={selectedLesson}
@@ -419,13 +475,11 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
</div>
)}
{/* Info Box */}
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
<h4 className="font-semibold text-yellow-900 mb-2 text-sm">¿Qué sucederá?</h4>
<ul className="text-xs text-yellow-800 space-y-1">
<li> La lección se convertirá en un quiz con las {selectedTemplate.name} preguntas de la plantilla</li>
<li> Se configurará con <strong>1 solo intento</strong> por alumno</li>
<li> Las calificaciones se sincronizarán con la base de datos MySQL</li>
<li> La lección se convertirá en un quiz con las preguntas de la plantilla</li>
<li> Se configurará con 1 solo intento por alumno</li>
<li> Los alumnos podrán revisar sus respuestas después de completar</li>
</ul>
</div>
@@ -436,7 +490,7 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
type="button"
onClick={() => {
setShowApplyModal(false);
setSelectedTemplate(null);
resetApplyState();
}}
className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
>
@@ -459,26 +513,27 @@ export default function TestTemplateManager({ onSelectTemplate, onCreateTemplate
);
}
// Lesson Selector Component
function LessonSelector({ courseId, selectedLesson, onSelect }: {
courseId: string;
function LessonSelector({
courseId,
selectedLesson,
onSelect,
}: {
courseId: string;
selectedLesson: string;
onSelect: (lessonId: string) => void;
}) {
const [lessons, setLessons] = useState<any[]>([]);
const [modules, setModules] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadLessons = async () => {
try {
setLoading(true);
const course = await cmsApi.getCourse(courseId);
if (course.modules) {
const allLessons = course.modules.flatMap((m: any) => m.lessons || []);
setLessons(allLessons);
}
const course = await cmsApi.getCourseWithFullOutline(courseId);
setModules(course.modules || []);
} catch (error) {
console.error('Failed to load lessons:', error);
setModules([]);
} finally {
setLoading(false);
}
@@ -490,7 +545,8 @@ function LessonSelector({ courseId, selectedLesson, onSelect }: {
return <div className="text-sm text-gray-500">Cargando lecciones...</div>;
}
if (lessons.length === 0) {
const totalLessons = modules.reduce((acc, m) => acc + (m.lessons?.length || 0), 0);
if (totalLessons === 0) {
return <div className="text-sm text-red-600">Este curso no tiene lecciones</div>;
}
@@ -501,10 +557,14 @@ function LessonSelector({ courseId, selectedLesson, onSelect }: {
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="">Selecciona una lección...</option>
{lessons.map((lesson) => (
<option key={lesson.id} value={lesson.id}>
{lesson.title} ({lesson.content_type || 'Sin contenido'})
</option>
{modules.map((mod) => (
<optgroup key={mod.id} label={mod.title}>
{(mod.lessons || []).map((lesson: any) => (
<option key={lesson.id} value={lesson.id}>
{lesson.title}
</option>
))}
</optgroup>
))}
</select>
);
@@ -47,7 +47,8 @@ export default function HotspotBlock({
try {
const data = await cmsApi.generateHotspots(lessonId, { image_url: imageUrl });
// Handle different response formats from AI
let hotspotsArray = Array.isArray(data) ? data : (data.hotspots || data.items || []);
const raw: any = data;
let hotspotsArray = Array.isArray(raw) ? raw : (raw.hotspots || raw.items || []);
if (!Array.isArray(hotspotsArray)) {
throw new Error("La respuesta de la IA no es un array válido");
+1 -1
View File
@@ -32,7 +32,7 @@ export const BrandingProvider: React.FC<{ children: React.ReactNode }> = ({ chil
return;
}
try {
const data = await cmsApi.getBranding(user.organization_id);
const data = await cmsApi.getBranding();
// Translate BrandingResponse to Organization shape (partial)
const orgData = {
id: user.organization_id,
+10 -8
View File
@@ -1,3 +1,6 @@
const STUDIO_DOMAIN = process.env.NEXT_PUBLIC_STUDIO_DOMAIN || 'studio.norteamericano.com';
const LEARNING_DOMAIN = process.env.NEXT_PUBLIC_LEARNING_DOMAIN || 'learning.norteamericano.com';
const getApiBaseUrl = (defaultPort: string, envVar?: string) => {
// Prefer explicit environment configuration when available. This allows production
// deployments to use a dedicated API prefix like `/cms-api` and avoids collisions
@@ -11,11 +14,11 @@ const getApiBaseUrl = (defaultPort: string, envVar?: string) => {
const protocol = window.location.protocol;
// Producción - dominios específicos (fallback sin prefijo)
if (hostname === 'studio.norteamericano.com') {
return `${protocol}//studio.norteamericano.com`;
if (hostname === STUDIO_DOMAIN) {
return `${protocol}//${STUDIO_DOMAIN}`;
}
if (hostname === 'learning.norteamericano.com') {
return `${protocol}//learning.norteamericano.com`;
if (hostname === LEARNING_DOMAIN) {
return `${protocol}//${LEARNING_DOMAIN}`;
}
// Desarrollo local
@@ -27,8 +30,8 @@ const getApiBaseUrl = (defaultPort: string, envVar?: string) => {
export const API_BASE_URL = getApiBaseUrl("3001", process.env.NEXT_PUBLIC_CMS_API_URL);
const getLmsBaseUrl = (envVar?: string) => {
if (typeof window !== 'undefined' && window.location.hostname === 'studio.norteamericano.com') {
return `${window.location.protocol}//studio.norteamericano.com/lms-api`;
if (typeof window !== 'undefined' && window.location.hostname === STUDIO_DOMAIN) {
return `${window.location.protocol}//${STUDIO_DOMAIN}/lms-api`;
}
return getApiBaseUrl("3002", envVar);
};
@@ -1433,8 +1436,7 @@ export interface CreateSectionPayload {
}
export interface TestTemplateFilters {
level?: CourseLevel;
course_type?: CourseType;
mysql_course_id?: number;
test_type?: TestType;
tags?: string;
search?: string;
File diff suppressed because one or more lines are too long