refactor: Remove unused variables and add dead code allowances for better clarity

This commit is contained in:
2026-04-10 10:50:14 -04:00
parent 53e5ef4d0b
commit 0c039ebfbc
10 changed files with 44 additions and 19 deletions
+2 -1
View File
@@ -948,7 +948,7 @@ pub async fn run_transcription_task(pool: PgPool, lesson_id: Uuid) -> Result<(),
let full_text = transcription_result["text"].as_str().unwrap_or(""); let full_text = transcription_result["text"].as_str().unwrap_or("");
if !full_text.is_empty() { if !full_text.is_empty() {
tracing::info!("Triggering AI summary for lesson {}", lesson_id); tracing::info!("Triggering AI summary for lesson {}", lesson_id);
if let Ok((summary, input_tokens, output_tokens)) = generate_summary_with_ollama(full_text, lesson_id, &pool).await { if let Ok((summary, _input_tokens, _output_tokens)) = generate_summary_with_ollama(full_text, lesson_id, &pool).await {
tracing::info!("Summary generated successfully for lesson {}", lesson_id); tracing::info!("Summary generated successfully for lesson {}", lesson_id);
let _ = sqlx::query("UPDATE lessons SET summary = $1 WHERE id = $2") let _ = sqlx::query("UPDATE lessons SET summary = $1 WHERE id = $2")
.bind(summary) .bind(summary)
@@ -2879,6 +2879,7 @@ pub async fn get_organization(
} }
/// GET /organization - Public endpoint (returns default organization) /// GET /organization - Public endpoint (returns default organization)
#[allow(dead_code)]
pub async fn get_public_organization( pub async fn get_public_organization(
State(pool): State<PgPool>, State(pool): State<PgPool>,
) -> Result<Json<Organization>, StatusCode> { ) -> Result<Json<Organization>, StatusCode> {
@@ -1,3 +1,5 @@
#![allow(dead_code)]
use axum::{ use axum::{
Json, Json,
extract::{Path, Query, State}, extract::{Path, Query, State},
@@ -9,7 +9,6 @@ use axum::{
use common::ai::{self, generate_embedding}; use common::ai::{self, generate_embedding};
use common::models::QuestionBank; use common::models::QuestionBank;
use common::middleware::Org; use common::middleware::Org;
use reqwest::Client;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
@@ -77,7 +76,7 @@ pub async fn generate_question_embeddings(
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
let total = questions.len(); let _total = questions.len();
let mut processed = 0; let mut processed = 0;
let mut failed = 0; let mut failed = 0;
@@ -280,12 +279,12 @@ pub async fn semantic_search(
let mut param_idx = 3; let mut param_idx = 3;
if let Some(ref question_type) = filters.question_type { if filters.question_type.is_some() {
param_idx += 1; param_idx += 1;
query.push_str(&format!(" AND question_type::text = ${}", param_idx)); query.push_str(&format!(" AND question_type::text = ${}", param_idx));
} }
if let Some(ref difficulty) = filters.difficulty { if filters.difficulty.is_some() {
param_idx += 1; param_idx += 1;
query.push_str(&format!(" AND difficulty = ${}", param_idx)); query.push_str(&format!(" AND difficulty = ${}", param_idx));
} }
@@ -137,6 +137,7 @@ async fn connect_mysql_pool(env_var: &str) -> Result<sqlx::MySqlPool, (StatusCod
// ==================== Planes de Estudio y Cursos de MySQL ==================== // ==================== Planes de Estudio y Cursos de MySQL ====================
#[derive(Debug, sqlx::FromRow, Serialize, Deserialize)] #[derive(Debug, sqlx::FromRow, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct MySqlStudyPlan { pub struct MySqlStudyPlan {
pub id: i32, pub id: i32,
pub mysql_id: i32, pub mysql_id: i32,
@@ -149,6 +150,7 @@ pub struct MySqlStudyPlan {
} }
#[derive(Debug, sqlx::FromRow, Serialize, Deserialize)] #[derive(Debug, sqlx::FromRow, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct MySqlCourse { pub struct MySqlCourse {
pub id: i32, pub id: i32,
pub mysql_id: i32, pub mysql_id: i32,
@@ -1012,6 +1014,7 @@ fn parse_mysql_answers(
// ==================== Integración con MySQL ==================== // ==================== Integración con MySQL ====================
/// GET /api/question-bank/mysql-courses - Listar cursos de MySQL para importación /// GET /api/question-bank/mysql-courses - Listar cursos de MySQL para importación
#[allow(dead_code)]
pub async fn list_mysql_courses( pub async fn list_mysql_courses(
Org(_org_ctx): Org, Org(_org_ctx): Org,
State(_pool): State<PgPool>, State(_pool): State<PgPool>,
@@ -1514,6 +1517,7 @@ pub async fn import_all_from_mysql(
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[allow(dead_code)]
pub struct ImportResult { pub struct ImportResult {
pub imported: i32, pub imported: i32,
pub skipped: i32, pub skipped: i32,
@@ -1549,6 +1553,7 @@ pub struct MySqlQuestionFull {
} }
#[derive(Debug, sqlx::FromRow)] #[derive(Debug, sqlx::FromRow)]
#[allow(dead_code)]
struct MySqlQuestion { struct MySqlQuestion {
id_pregunta: i32, id_pregunta: i32,
descripcion: String, descripcion: String,
@@ -1565,6 +1570,7 @@ struct MySqlQuestion {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct AIGenerateQuestionPayload { pub struct AIGenerateQuestionPayload {
pub question_text: Option<String>, pub question_text: Option<String>,
#[allow(dead_code)]
pub question_type: Option<String>, pub question_type: Option<String>,
pub difficulty: Option<String>, pub difficulty: Option<String>,
pub skill: Option<String>, pub skill: Option<String>,
@@ -1588,6 +1594,7 @@ pub async fn ai_generate_question(
use std::time::Duration; use std::time::Duration;
let question_text = payload.question_text.unwrap_or_else(|| "Pregunta de gramática inglesa".to_string()); let question_text = payload.question_text.unwrap_or_else(|| "Pregunta de gramática inglesa".to_string());
let question_type = payload.question_type.unwrap_or_else(|| "multiple-choice".to_string());
let difficulty = payload.difficulty.unwrap_or_else(|| "medium".to_string()); let difficulty = payload.difficulty.unwrap_or_else(|| "medium".to_string());
let skill = payload.skill.unwrap_or_else(|| "grammar".to_string()); let skill = payload.skill.unwrap_or_else(|| "grammar".to_string());
@@ -1597,6 +1604,7 @@ pub async fn ai_generate_question(
Create a multiple-choice question with the following parameters: Create a multiple-choice question with the following parameters:
- Topic/Context: {} - Topic/Context: {}
- Question type: {}
- Difficulty: {} - Difficulty: {}
- Skill assessed: {} - Skill assessed: {}
@@ -1607,7 +1615,7 @@ pub async fn ai_generate_question(
"correct_answer": 0, "correct_answer": 0,
"explanation": "Detailed explanation of why this is correct" "explanation": "Detailed explanation of why this is correct"
}}"#, }}"#,
question_text, difficulty, skill question_text, question_type, difficulty, skill
); );
// Llamar a Ollama AI con tiempo de espera extendido // Llamar a Ollama AI con tiempo de espera extendido
@@ -1800,8 +1808,8 @@ async fn generate_course_structure<'a>(
course_id: Uuid, course_id: Uuid,
org_id: Uuid, org_id: Uuid,
course_type: &str, course_type: &str,
level: &str, _level: &str,
course_name: &str, _course_name: &str,
) -> Result<(i32, i32), String> { ) -> Result<(i32, i32), String> {
// Definir la estructura de módulos basada en el tipo de curso // Definir la estructura de módulos basada en el tipo de curso
// Regular (40h): 4 módulos // Regular (40h): 4 módulos
@@ -1892,6 +1900,7 @@ struct SamDiagnosticoQuestion {
pub id_curso: i32, pub id_curso: i32,
pub id_pregunta: i32, pub id_pregunta: i32,
pub pregunta_nombre: Option<String>, pub pregunta_nombre: Option<String>,
#[allow(dead_code)]
pub tipo_pregunta: Option<String>, pub tipo_pregunta: Option<String>,
/// Opciones separadas por '|||' (GROUP_CONCAT) /// Opciones separadas por '|||' (GROUP_CONCAT)
pub opciones: Option<String>, pub opciones: Option<String>,
+3 -3
View File
@@ -115,7 +115,7 @@ pub async fn sync_sam_students(
.flatten(); .flatten();
match existing_user { match existing_user {
Some((user_id, existing_sam_id)) => { Some((user_id, _existing_sam_id)) => {
// Actualizar usuario existente con información de SAM // Actualizar usuario existente con información de SAM
let update_result = sqlx::query( let update_result = sqlx::query(
r#" r#"
@@ -373,8 +373,8 @@ pub async fn get_sam_student_courses(
/// POST /api/sam/sync-all /// POST /api/sam/sync-all
/// Sincronización completa: estudiantes + asignaciones /// Sincronización completa: estudiantes + asignaciones
pub async fn sync_all_sam( pub async fn sync_all_sam(
org: Org, _org: Org,
claims: Claims, _claims: Claims,
State(pool): State<PgPool>, State(pool): State<PgPool>,
) -> Result<Json<SamSyncResponse>, (StatusCode, String)> { ) -> Result<Json<SamSyncResponse>, (StatusCode, String)> {
let mut errors = Vec::new(); let mut errors = Vec::new();
@@ -270,7 +270,7 @@ pub async fn get_test_template(
pub async fn update_test_template( pub async fn update_test_template(
Org(org_ctx): Org, Org(org_ctx): Org,
Path(template_id): Path<Uuid>, Path(template_id): Path<Uuid>,
claims: Claims, _claims: Claims,
State(pool): State<PgPool>, State(pool): State<PgPool>,
Json(payload): Json<UpdateTestTemplatePayload>, Json(payload): Json<UpdateTestTemplatePayload>,
) -> Result<Json<TestTemplate>, (StatusCode, String)> { ) -> Result<Json<TestTemplate>, (StatusCode, String)> {
@@ -511,7 +511,7 @@ pub struct CreateSectionPayload {
/// DELETE /api/test-templates/:template_id/sections/:section_id - Eliminar una sección /// DELETE /api/test-templates/:template_id/sections/:section_id - Eliminar una sección
pub async fn delete_template_section( pub async fn delete_template_section(
Org(org_ctx): Org, Org(_org_ctx): Org,
Path((template_id, section_id)): Path<(Uuid, Uuid)>, Path((template_id, section_id)): Path<(Uuid, Uuid)>,
State(pool): State<PgPool>, State(pool): State<PgPool>,
) -> Result<StatusCode, (StatusCode, String)> { ) -> Result<StatusCode, (StatusCode, String)> {
@@ -540,7 +540,7 @@ pub async fn delete_template_section(
pub async fn apply_template_to_lesson( pub async fn apply_template_to_lesson(
Org(org_ctx): Org, Org(org_ctx): Org,
Path(template_id): Path<Uuid>, Path(template_id): Path<Uuid>,
claims: Claims, _claims: Claims,
State(pool): State<PgPool>, State(pool): State<PgPool>,
Json(payload): Json<ApplyTemplatePayload>, Json(payload): Json<ApplyTemplatePayload>,
) -> Result<StatusCode, (StatusCode, String)> { ) -> Result<StatusCode, (StatusCode, String)> {
@@ -1075,6 +1075,8 @@ pub async fn generate_questions_with_rag(
tracing::info!("La búsqueda semántica encontró {} preguntas similares", mysql_questions.len()); tracing::info!("La búsqueda semántica encontró {} preguntas similares", mysql_questions.len());
if mysql_questions.is_empty() { if mysql_questions.is_empty() {
tracing::info!(
"Sin coincidencias semánticas para el tema; recurso a búsqueda por palabras clave. topic={} course_id={:?}",
topic, topic,
payload.course_id payload.course_id
); );
@@ -1124,6 +1126,8 @@ pub async fn generate_questions_with_rag(
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("El recurso a palabras clave falló: {}", e)))?; .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("El recurso a palabras clave falló: {}", e)))?;
if mysql_questions.is_empty() { if mysql_questions.is_empty() {
tracing::info!(
"Sin coincidencias por palabras clave; recurso a preguntas importadas por curso. course_id={:?}",
payload.course_id payload.course_id
); );
@@ -1219,6 +1223,8 @@ pub async fn generate_questions_with_rag(
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("La búsqueda por palabras clave falló: {}", e)))?; .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("La búsqueda por palabras clave falló: {}", e)))?;
if mysql_questions.is_empty() { if mysql_questions.is_empty() {
tracing::info!(
"Sin resultados semánticos ni por palabras clave; recurso a preguntas importadas por curso. course_id={:?}",
payload.course_id payload.course_id
); );
@@ -1337,6 +1343,8 @@ pub async fn generate_questions_with_rag(
} }
if mysql_questions.is_empty() { if mysql_questions.is_empty() {
tracing::warn!(
"No se encontraron preguntas importadas para org={} course_id={:?} topic={:?}; recurso a preguntas de toda la organización",
org_ctx.id, org_ctx.id,
payload.course_id, payload.course_id,
payload.topic payload.topic
@@ -1828,6 +1836,7 @@ pub struct RagGenerationPayload {
} }
#[derive(Debug, sqlx::FromRow)] #[derive(Debug, sqlx::FromRow)]
#[allow(dead_code)]
struct QuestionBankForRAG { struct QuestionBankForRAG {
descripcion: String, descripcion: String,
options: Option<serde_json::Value>, options: Option<serde_json::Value>,
@@ -1839,6 +1848,7 @@ struct QuestionBankForRAG {
} }
#[derive(Debug, sqlx::FromRow)] #[derive(Debug, sqlx::FromRow)]
#[allow(dead_code)]
struct MySqlQuestion { struct MySqlQuestion {
descripcion: String, descripcion: String,
id_tipo_pregunta: i32, id_tipo_pregunta: i32,
+6 -5
View File
@@ -56,11 +56,12 @@ impl WebhookService {
match res { match res {
Ok(response) => { Ok(response) => {
if !response.status().is_success() { if !response.status().is_success() {
"El envío del webhook a {} (evento: {}) falló con estado {}", tracing::error!(
url, "El envío del webhook a {} (evento: {}) falló con estado {}",
event_type, url,
response.status() event_type,
); response.status()
);
} else { } else {
tracing::info!( tracing::info!(
"Webhook enviado con éxito a {} (evento: {})", "Webhook enviado con éxito a {} (evento: {})",
@@ -272,6 +272,7 @@ pub async fn semantic_search_knowledge(
// ==================== Estructuras de Ayuda ==================== // ==================== Estructuras de Ayuda ====================
#[derive(Debug, sqlx::FromRow, Clone)] #[derive(Debug, sqlx::FromRow, Clone)]
#[allow(dead_code)]
struct KnowledgeBaseEntry { struct KnowledgeBaseEntry {
id: Uuid, id: Uuid,
organization_id: Uuid, organization_id: Uuid,
+1
View File
@@ -117,6 +117,7 @@ pub fn get_model_for_task(task: &str) -> String {
} }
/// Crear un cliente reqwest que acepte certificados inválidos (para desarrollo con certificados autofirmados) /// Crear un cliente reqwest que acepte certificados inválidos (para desarrollo con certificados autofirmados)
#[allow(dead_code)]
fn create_insecure_client() -> Result<reqwest::Client, AiError> { fn create_insecure_client() -> Result<reqwest::Client, AiError> {
reqwest::Client::builder() reqwest::Client::builder()
.danger_accept_invalid_certs(true) .danger_accept_invalid_certs(true)
+1
View File
@@ -1182,6 +1182,7 @@ pub struct PublicProfile {
#[derive(Debug, Serialize, Deserialize, sqlx::Type, Clone, PartialEq)] #[derive(Debug, Serialize, Deserialize, sqlx::Type, Clone, PartialEq)]
#[sqlx(type_name = "course_level", rename_all = "lowercase")] #[sqlx(type_name = "course_level", rename_all = "lowercase")]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
#[allow(non_camel_case_types)]
pub enum CourseLevel { pub enum CourseLevel {
Beginner, Beginner,
Beginner_1, Beginner_1,