diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d52ba35..ad10b53 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -97,7 +97,7 @@ jobs: # Extraer changelog para la versión actual if [ -f "CHANGELOG.md" ]; then # Buscar la sección de la versión actual - awk '/## \["'"${{ needs.check-version.outputs.version }}"'"\]/{flag=1; next} /## \[/{flag=0} flag' CHANGELOG.md > current_changelog.md + awk '/## \['"${{ needs.check-version.outputs.version }}"'\]/{flag=1; next} /## \[/{flag=0} flag' CHANGELOG.md > current_changelog.md if [ -s current_changelog.md ]; then echo "Found changelog entry for version ${{ needs.check-version.outputs.version }}" diff --git a/CHANGELOG.md b/CHANGELOG.md index 19518ba..cbe7150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Todas las modificaciones importantes del proyecto se documentarán en este archivo. +## [2.0.2] — 2026-01-08 +- Paginación en la lista de estudiantes en el panel de administración. +- Nueva forma de mostrar las estadísticas generales en el panel de administración. +- Uso de arquitectura de plantillas Mustache para todas las vistas del bloque. +- Refactorización completa del código para separar lógica de presentación. +- Mejora en la mantenibilidad y escalabilidad del código. +- Optimización del rendimiento en búsquedas. +- Pequeñas mejoras de seguridad. + ## [2.0.1] — 2025-12-22 - Correción de un error (al actualizar de la versión 1.x a 2.0.0) que causaba fallos en la base de datos. - Lectura correcta del CHANGELOG en el flujo de trabajo de GitHub Actions. diff --git a/README.md b/README.md index a0a5db1..0a16623 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ El profesor cuenta con una vista ejecutiva desde el bloque, donde puede monitori Un panel de administración que centraliza el seguimiento grupal. Permite visualizar quiénes han completado el proceso, quiénes están en curso y gestionar los resultados colectivos para adaptar la estrategia pedagógica del aula.

- Panel de Administración + Panel de Administración

**Seguimiento Individualizado y Detallado** diff --git a/admin_view.php b/admin_view.php index fb66da1..2f0e1aa 100644 --- a/admin_view.php +++ b/admin_view.php @@ -1,11 +1,22 @@ libdir . '/tablelib.php'); -$courseid = optional_param('cid', 0, PARAM_INT); +$courseid = optional_param('cid', 0, PARAM_INT); // Using 'cid' to be consistent with other files in this block +if (!$courseid) { + print_error('missingparam', 'block_personality_test'); +} -if ($courseid == SITEID || !$courseid) { +if ($courseid == SITEID) { redirect($CFG->wwwroot); } @@ -16,441 +27,270 @@ require_login($course, false); -// Silent redirect for users without report capability (e.g., students) -if (!has_capability('block/personality_test:viewreports', $context)) { +// Check if the block is added to the course +if (!$DB->record_exists('block_instances', array('blockname' => 'personality_test', 'parentcontextid' => $context->id))) { + redirect(new moodle_url('/course/view.php', array('id' => $courseid))); +} + +// Friendly redirect for unauthorized users +if (!has_capability('block/personality_test:viewreports', $context) && !is_siteadmin()) { redirect(new moodle_url('/course/view.php', array('id' => $courseid))); } +// Parameters $action = optional_param('action', '', PARAM_ALPHA); $userid = optional_param('userid', 0, PARAM_INT); +$page = optional_param('page', 0, PARAM_INT); +$perpage = optional_param('perpage', 20, PARAM_INT); +$search = optional_param('search', '', PARAM_NOTAGS); -// Procesar acciones +$admin_url = new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)); +$PAGE->set_url($admin_url); + +// Handle Delete Action if ($action === 'delete' && $userid && confirm_sesskey()) { $confirm = optional_param('confirm', 0, PARAM_INT); if ($confirm) { - // Defensive: allow deletion only for users that are students in this course. + // Privacy check $targetuser = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST); if (!is_siteadmin() && ( !is_enrolled($context, $targetuser, 'block/personality_test:taketest', true) || has_capability('block/personality_test:viewreports', $context, $userid) || is_siteadmin($userid) )) { - redirect(new moodle_url('/course/view.php', array('id' => $courseid))); + redirect(new moodle_url('/course/view.php', array('id' => $courseid))); } - // Eliminar registro global del test del usuario + $DB->delete_records('personality_test', array('user' => $userid)); - redirect(new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)), - get_string('participation_deleted', 'block_personality_test')); + redirect($admin_url, get_string('participation_deleted', 'block_personality_test')); } } -$PAGE->set_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)); $title = get_string('admin_manage_title', 'block_personality_test'); $PAGE->set_pagelayout('standard'); $PAGE->set_title($title . " : " . $course->fullname); $PAGE->set_heading($title . " : " . $course->fullname); +$PAGE->requires->css('/blocks/personality_test/styles.css'); -$PAGE->requires->css(new moodle_url('/blocks/personality_test/styles.css')); +// Template Data Construction +$data = [ + 'title' => $title, + 'icon_url' => (new moodle_url('/blocks/personality_test/pix/icon.svg'))->out(), + 'description' => format_text(get_string('admin_dashboard_description', 'block_personality_test'), FORMAT_HTML), + 'courseid' => $courseid, + 'admin_url' => $admin_url->out(false), + 'csv_url' => (new moodle_url('/blocks/personality_test/download_csv.php', ['courseid' => $courseid, 'sesskey' => sesskey()]))->out(false), + 'pdf_url' => (new moodle_url('/blocks/personality_test/download_pdf.php', ['courseid' => $courseid, 'sesskey' => sesskey()]))->out(false), + 'course_url' => (new moodle_url('/course/view.php', ['id' => $courseid]))->out(false), + 'search_term' => $search +]; -echo $OUTPUT->header(); -echo "
"; - -// Generate personality test icon for header -$iconurl = new moodle_url('/blocks/personality_test/pix/personality_test_icon.svg'); -$icon_html = 'Personality Test Icon'; - -echo "

" . $icon_html . get_string('admin_manage_title', 'block_personality_test') . "

"; - -// Confirmación de eliminación -if ($action === 'delete' && $userid) { - $user = $DB->get_record('user', array('id' => $userid), 'firstname, lastname'); - if ($user) { - echo "
"; - echo "

" . get_string('confirm_delete', 'block_personality_test') . "

"; - echo "

" . get_string('confirm_delete_message', 'block_personality_test', fullname($user)) . "

"; - echo ""; - echo "
"; - } -} else { - // Description banner (match other admin dashboards) - echo "
"; - echo format_text(get_string('admin_dashboard_description', 'block_personality_test'), FORMAT_HTML); - echo "
"; - - // Obtener estadísticas - // Get enrolled users who can take the test (defaults to student archetype) - $enrolled_students = get_enrolled_users($context, 'block/personality_test:taketest', 0, 'u.id, u.firstname, u.lastname'); - $enrolled_ids = array_keys($enrolled_students); - - // Defensive: ensure only students show in admin tables (exclude report-capable users). - $student_ids = array(); - foreach ($enrolled_ids as $candidateid) { - $candidateid = (int)$candidateid; - if (is_siteadmin($candidateid)) { - continue; - } - if (has_capability('block/personality_test:viewreports', $context, $candidateid)) { - continue; - } - $student_ids[] = $candidateid; - } - $enrolled_ids = $student_ids; +// Handle Delete Confirmation +$user = $DB->get_record('user', array('id' => $userid), 'firstname, lastname'); +if ($user && $action === 'delete' && !$confirm) { + $data['delete_confirmation'] = true; + $data['confirm_message'] = get_string('confirm_delete_message', 'block_personality_test', fullname($user)); + $data['confirm_url'] = (new moodle_url('/blocks/personality_test/admin_view.php', [ + 'cid' => $courseid, + 'action' => 'delete', + 'userid' => $userid, + 'confirm' => 1, + 'sesskey' => sesskey() + ]))->out(false); + $data['cancel_url'] = $admin_url->out(false); + + echo $OUTPUT->header(); + echo $OUTPUT->render_from_template('block_personality_test/admin_view', $data); + echo $OUTPUT->footer(); + exit; +} + +// 1. Get Enrolled Users Helper +// We use 'block/personality_test:taketest' capability to filter students +list($esql, $params) = get_enrolled_sql($context, 'block/personality_test:taketest', 0, true); + +// 2. Statistics (Count only) +$sql_enrolled = "SELECT COUNT(DISTINCT u.id) FROM {user} u JOIN ($esql) je ON je.id = u.id WHERE u.deleted = 0"; +$total_students = $DB->count_records_sql($sql_enrolled, $params); + +// SQL for completed/in-progress +$sql_completed_count = "SELECT COUNT(pt.id) FROM {personality_test} pt JOIN ($esql) je ON je.id = pt.user WHERE pt.is_completed = 1"; +$completed_tests = $DB->count_records_sql($sql_completed_count, $params); + +$sql_all_responses = "SELECT COUNT(pt.id) FROM {personality_test} pt JOIN ($esql) je ON je.id = pt.user"; +$count_responses = $DB->count_records_sql($sql_all_responses, $params); +$in_progress_tests = $count_responses - $completed_tests; + +$completion_rate = $total_students > 0 ? round(($completed_tests / $total_students) * 100, 1) : 0; + +$data['total_students'] = $total_students; +$data['completed_tests'] = $completed_tests; +$data['in_progress_tests'] = $in_progress_tests; +$data['completion_rate'] = $completion_rate; +$data['has_completed'] = ($completed_tests > 0); + +// 3. Stats Optimization +if ($completed_tests > 0) { + // Averages + $sql_avg = "SELECT + AVG(extraversion) as avg_extraversion, + AVG(introversion) as avg_introversion, + AVG(sensing) as avg_sensing, + AVG(intuition) as avg_intuition, + AVG(thinking) as avg_thinking, + AVG(feeling) as avg_feeling, + AVG(judging) as avg_judging, + AVG(perceptive) as avg_perceptive + FROM {personality_test} pt + JOIN ($esql) je ON je.id = pt.user + WHERE pt.is_completed = 1"; - // Total students in course - $total_students = count($enrolled_ids); + $avgs = $DB->get_record_sql($sql_avg, $params); + + // Calculate Distribution for Charts (Colors from block_personality_test.php or charts.js palette) + $helper_dim = function($avg1, $avg2, $color1, $color2, $l1, $l2) { + $val1 = round($avg1, 1); + $val2 = round($avg2, 1); + return [ + 'left_label' => $l1, + 'right_label' => $l2, + 'left_avg' => $val1, + 'right_avg' => $val2, + 'left_color' => $color1, + 'right_color' => $color2 + ]; + }; - // Obtener participantes con información del usuario PRIMERO (antes de calcular estadísticas) - $userfields = \core_user\fields::for_name()->with_userpic()->get_sql('u', false, '', '', false)->selects; - $participants = array(); - if (!empty($enrolled_ids)) { - list($insql, $params) = $DB->get_in_or_equal($enrolled_ids, SQL_PARAMS_NAMED); - $sql = "SELECT pt.*, {$userfields} - FROM {personality_test} pt - JOIN {user} u ON pt.user = u.id - WHERE pt.user $insql - ORDER BY pt.created_at DESC"; - - $participants = $DB->get_records_sql($sql, $params); - } + // Using colors from the previous implementation / charts.js + // Introversion (Blue) / Extraversion (Orange) -> Note: block_personality_test.php uses introversion as blueish + $data['dimension_stats'] = [ + $helper_dim($avgs->avg_introversion, $avgs->avg_extraversion, '#005B9A', '#FF8200', get_string('Introvertido', 'block_personality_test'), get_string('Extrovertido', 'block_personality_test')), + $helper_dim($avgs->avg_sensing, $avgs->avg_intuition, '#00B5E2', '#FFB600', get_string('Sensing', 'block_personality_test'), get_string('Intuicion', 'block_personality_test')), + $helper_dim($avgs->avg_thinking, $avgs->avg_feeling, '#78BE20', '#652C8F', get_string('Pensamiento', 'block_personality_test'), get_string('Sentimiento', 'block_personality_test')), + $helper_dim($avgs->avg_judging, $avgs->avg_perceptive, '#AA182C', '#0077C8', get_string('Juicio', 'block_personality_test'), get_string('Percepcion', 'block_personality_test')) + ]; + + // Most Common Types Calculation + // We need to fetch all completed results to compute types correctly in PHP + // Ideally we would do this in SQL but it varies per DB engine. + $sql_all_completed = "SELECT pt.id, pt.extraversion, pt.introversion, pt.sensing, pt.intuition, pt.thinking, pt.feeling, pt.judging, pt.perceptive + FROM {personality_test} pt + JOIN ($esql) je ON je.id = pt.user + WHERE pt.is_completed = 1"; + $all_completed = $DB->get_records_sql($sql_all_completed, $params); - // Count participants who are enrolled in this course - $completed_tests = 0; - $in_progress_tests = 0; - if (!empty($enrolled_ids)) { - list($insql, $params) = $DB->get_in_or_equal($enrolled_ids, SQL_PARAMS_NAMED); - - // Count completed tests - $params_completed = $params; - $params_completed['completed'] = 1; - $completed_tests = $DB->count_records_select('personality_test', "user $insql AND is_completed = :completed", $params_completed); + $type_counts = []; + foreach ($all_completed as $row) { + $type = ''; + $type .= ($row->extraversion > $row->introversion) ? 'E' : 'I'; + $type .= ($row->sensing > $row->intuition) ? 'S' : 'N'; + $type .= ($row->thinking >= $row->feeling) ? 'T' : 'F'; + $type .= ($row->judging > $row->perceptive) ? 'J' : 'P'; - // Count in-progress tests - $params_progress = $params; - $params_progress['completed'] = 0; - $in_progress_tests = $DB->count_records_select('personality_test', "user $insql AND is_completed = :completed", $params_progress); + if (!isset($type_counts[$type])) { + $type_counts[$type] = 0; + } + $type_counts[$type]++; } + arsort($type_counts); + $top_4 = array_slice($type_counts, 0, 4); - echo "
"; - - // Total students card - echo "
"; - echo "
"; - echo "
"; - echo ""; - echo "
" . get_string('total_students', 'block_personality_test') . "
"; - echo "

" . $total_students . "

"; - echo "
"; - echo "
"; - echo "
"; - - // Completed tests card - echo "
"; - echo "
"; - echo "
"; - echo ""; - echo "
" . get_string('completed_tests', 'block_personality_test') . "
"; - echo "

" . $completed_tests . "

"; - echo "
"; - echo "
"; - echo "
"; - - // In progress tests card - echo "
"; - echo "
"; - echo "
"; - echo ""; - echo "
" . get_string('in_progress_tests', 'block_personality_test') . "
"; - echo "

" . $in_progress_tests . "

"; - echo "
"; - echo "
"; - echo "
"; + $formatted_top_types = []; + $rank = 1; + // Color palette for types + $type_colors = [ + '#005B9A', '#FF8200', '#FFB600', '#00B5E2', + '#78BE20', '#2C5234', '#652C8F', '#91268F', + '#D0006F', '#AA182C', '#8B0304', '#E35205' + ]; + $color_idx = 0; - // Completion rate card - $completion_rate = $total_students > 0 ? round(($completed_tests / $total_students) * 100, 1) : 0; - echo "
"; - echo "
"; - echo "
"; - echo ''; - echo "
" . get_string('completion_rate', 'block_personality_test') . "
"; - echo "

" . $completion_rate . "%

"; - echo "
"; - echo "
"; - echo "
"; - - echo "
"; - - // General statistics section (only meaningful when there are completed tests) - if ($completed_tests > 0) { - echo "
"; - echo "
"; - echo "
"; - echo "
"; - echo "
" . get_string('general_statistics', 'block_personality_test') . "
"; - echo "
"; - echo "
"; - echo "
"; - - // Calculate MBTI type distribution - $type_distribution = array(); - if (!empty($participants)) { - foreach ($participants as $p) { - if ($p->is_completed == 1) { - $e_or_i = $p->extraversion > $p->introversion ? 'E' : 'I'; - $s_or_n = $p->sensing > $p->intuition ? 'S' : 'N'; - $t_or_f = $p->thinking >= $p->feeling ? 'T' : 'F'; - $j_or_p = $p->judging > $p->perceptive ? 'J' : 'P'; - $type = $e_or_i . $s_or_n . $t_or_f . $j_or_p; - if (!isset($type_distribution[$type])) { - $type_distribution[$type] = 0; - } - $type_distribution[$type]++; - } - } - } - - // Display top 4 most common types - arsort($type_distribution); - $top_types = array_slice($type_distribution, 0, 4, true); - - echo "
"; - echo "
" . get_string('most_common_types', 'block_personality_test') . "
"; - if (!empty($top_types)) { - echo "
    "; - foreach ($top_types as $type => $count) { - $percentage = $completed_tests > 0 ? round(($count / $completed_tests) * 100, 1) : 0; - echo "
  • "; - echo "" . $type . ""; - echo "" . $count . " (" . $percentage . "%)"; - echo "
  • "; - } - echo "
"; - } else { - echo "

" . get_string('no_data_available', 'block_personality_test') . "

"; - } - echo "
"; - - // Average dimension scores - echo "
"; - echo "
" . get_string('average_dimensions', 'block_personality_test') . "
"; - if ($completed_tests > 0) { - $avg_extraversion = 0; - $avg_introversion = 0; - $avg_sensing = 0; - $avg_intuition = 0; - $avg_thinking = 0; - $avg_feeling = 0; - $avg_judging = 0; - $avg_perceptive = 0; - - foreach ($participants as $p) { - if ($p->is_completed == 1) { - $avg_extraversion += $p->extraversion; - $avg_introversion += $p->introversion; - $avg_sensing += $p->sensing; - $avg_intuition += $p->intuition; - $avg_thinking += $p->thinking; - $avg_feeling += $p->feeling; - $avg_judging += $p->judging; - $avg_perceptive += $p->perceptive; - } - } - - $avg_extraversion = round($avg_extraversion / $completed_tests, 1); - $avg_introversion = round($avg_introversion / $completed_tests, 1); - $avg_sensing = round($avg_sensing / $completed_tests, 1); - $avg_intuition = round($avg_intuition / $completed_tests, 1); - $avg_thinking = round($avg_thinking / $completed_tests, 1); - $avg_feeling = round($avg_feeling / $completed_tests, 1); - $avg_judging = round($avg_judging / $completed_tests, 1); - $avg_perceptive = round($avg_perceptive / $completed_tests, 1); - - echo "
    "; - echo "
  • "; - echo "" . get_string('extraversion','block_personality_test') . " - " . get_string('introversion','block_personality_test') . ""; - echo "" . $avg_extraversion . " - " . $avg_introversion . ""; - echo "
  • "; - echo "
  • "; - echo "" . get_string('sensing','block_personality_test') . " - " . get_string('intuition','block_personality_test') . ""; - echo "" . $avg_sensing . " - " . $avg_intuition . ""; - echo "
  • "; - echo "
  • "; - echo "" . get_string('thinking','block_personality_test') . " - " . get_string('feeling','block_personality_test') . ""; - echo "" . $avg_thinking . " - " . $avg_feeling . ""; - echo "
  • "; - echo "
  • "; - echo "" . get_string('judging','block_personality_test') . " - " . get_string('perceptive','block_personality_test') . ""; - echo "" . $avg_judging . " - " . $avg_perceptive . ""; - echo "
  • "; - echo "
"; - } else { - echo "

" . get_string('no_data_available', 'block_personality_test') . "

"; - } - - echo "
"; - - echo "
"; // Cierra row de estadísticas - echo "
"; // Cierra card-body - echo "
"; // Cierra card - echo "
"; // Cierra col-12 - echo "
"; // Cierra row mt-4 + foreach ($top_4 as $t => $c) { + $formatted_top_types[] = [ + 'rank' => $rank++, + 'label' => $t, + 'count' => $c, + 'percentage' => round(($c / $completed_tests) * 100, 1), + 'color_hex' => $type_colors[$color_idx++ % count($type_colors)] + ]; } + $data['top_types'] = $formatted_top_types; +} - // Sección de Participants List - if (empty($participants)) { - echo "
"; - echo " "; - echo "
" . get_string('no_participants', 'block_personality_test') . "
"; - echo "

" . get_string('no_participants_message', 'block_personality_test') . "

"; - echo "
"; - } else { - echo "
"; - echo "
"; - echo "
" . get_string('participants_list', 'block_personality_test') . "
"; - echo "
"; - echo "
"; - - // Filtros y búsqueda - echo "
"; - echo "
"; - echo ""; - echo "
"; - echo "
"; - echo " "; - echo ""; - echo "
"; - echo "
"; - - // Tabla de participantes - echo "
"; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - - foreach ($participants as $participant) { - echo ""; - echo ""; - echo ""; - - // Estado y Progreso - echo ""; - - // Tipo MBTI (solo si está completado) - echo ""; - - echo ""; - echo ""; - echo ""; - } +// 4. Participants Table +$userfields = \core_user\fields::for_name()->with_userpic()->get_sql('u', false, '', '', false)->selects; +$where_search = ""; +$search_params = []; - echo ""; - echo "
" . get_string('student_name', 'block_personality_test') . "" . get_string('email', 'block_personality_test') . "" . get_string('status', 'block_personality_test') . "" . get_string('mbti_type', 'block_personality_test') . "" . get_string('test_date', 'block_personality_test') . "" . get_string('actions', 'block_personality_test') . "
"; - echo "
"; - $userpicture = new user_picture($participant); - $userpicture->size = 35; - echo $OUTPUT->render($userpicture); - echo "" . fullname($participant) . ""; - echo "
"; - echo "
" . $participant->email . ""; - if ($participant->is_completed == 1) { - echo "" . get_string('completed_status', 'block_personality_test') . ""; - } else { - // Calcular progreso - contar respuestas no nulas - $answered = 0; - for ($i = 1; $i <= 72; $i++) { - $field = 'q' . $i; - if (isset($participant->$field) && $participant->$field !== null && $participant->$field !== '') { - $answered++; - } - } - echo "" . get_string('in_progress_status', 'block_personality_test') . ""; - echo "
" . get_string('of_72_questions', 'block_personality_test', $answered) . ""; - } - echo "
"; - if ($participant->is_completed == 1) { - $mbti = ''; - $mbti .= ($participant->extraversion >= $participant->introversion) ? 'E' : 'I'; - $mbti .= ($participant->sensing > $participant->intuition) ? 'S' : 'N'; - $mbti .= ($participant->thinking >= $participant->feeling) ? 'T' : 'F'; - $mbti .= ($participant->judging > $participant->perceptive) ? 'J' : 'P'; - echo "" . $mbti . ""; - } else { - echo "-"; - } - echo "" . date('d/m/Y H:i', $participant->created_at) . ""; - echo " $participant->user, 'cid' => $courseid)) . - "' class='btn btn-sm btn-info mr-2 mt-1 mb-1' title='" . get_string('view_results', 'block_personality_test') . "'>"; - echo " " . get_string('view', 'block_personality_test'); - echo ""; - echo " $courseid, 'action' => 'delete', 'userid' => $participant->user, 'sesskey' => sesskey())) . - "' class='btn btn-sm btn-danger' title='" . get_string('delete_participation', 'block_personality_test') . "'>"; - echo " " . get_string('delete', 'block_personality_test'); - echo ""; - echo "
"; - echo "
"; - echo "
"; - echo "
"; - } +if (!empty($search)) { + $where_search = " AND (" . $DB->sql_like('u.firstname', ':s1', false) . " OR " . $DB->sql_like('u.lastname', ':s2', false) . " OR " . $DB->sql_like('u.email', ':s3', false) . ")"; + $search_params = ['s1' => "%$search%", 's2' => "%$search%", 's3' => "%$search%"]; } -// Botón para regresar al curso -echo "
"; -echo " $courseid)) . "' class='btn btn-secondary'>"; -echo " " . get_string('back_to_course', 'block_personality_test'); -echo ""; -echo "
"; +$sql_count_participants = "SELECT COUNT(pt.id) + FROM {personality_test} pt + JOIN {user} u ON pt.user = u.id + JOIN ($esql) je ON je.id = pt.user + WHERE 1=1 $where_search"; -echo "
"; +$total_rows = $DB->count_records_sql($sql_count_participants, array_merge($params, $search_params)); -// JavaScript para funcionalidad -echo ""; + + $list[] = $row; + } +} +$data['list'] = $list; + +$baseurl = new moodle_url('/blocks/personality_test/admin_view.php', ['cid' => $courseid]); +if ($search) { + $baseurl->param('search', $search); +} +$data['pagination'] = $OUTPUT->render(new paging_bar($total_rows, $page, $perpage, $baseurl, 'page')); +echo $OUTPUT->header(); +echo $OUTPUT->render_from_template('block_personality_test/admin_view', $data); echo $OUTPUT->footer(); -?> diff --git a/amd/build/charts.min.js b/amd/build/charts.min.js index b3b86c0..17676db 100644 --- a/amd/build/charts.min.js +++ b/amd/build/charts.min.js @@ -1,326 +1 @@ -define(["core/chartjs"], function(Chart) { - return { - init: function(mbtiData, aspectData, strings) { - var colorPalette = { - mbti: ["#005B9A","#FF8200","#FFB600","#00B5E2","#78BE20","#2C5234","#652C8F","#91268F","#D0006F","#AA182C","#8B0304","#E35205","#385CAD","#0077C8","#00263A","#00A9B7"], - introversion: ["#005B9A","#FF8200"], - sensacion: ["#00B5E2","#FFB600"], - pensamiento: ["#78BE20","#652C8F"], - juicio: ["#AA182C","#0077C8"] - }; - - function createMBTIChart() { - var ctx = document.getElementById("mbtiChart"); - if (ctx) { - ctx = ctx.getContext("2d"); - var labels = [], values = [], colors = []; - var colorIndex = 0; - - // Asegurarse de que mbtiData sea un objeto - if (typeof mbtiData === 'string') { - try { - mbtiData = JSON.parse(mbtiData); - } catch (e) { - console.error('Error al analizar mbtiData:', e); - } - } - - Object.keys(mbtiData).forEach(function(type) { - if (mbtiData[type] > 0) { - labels.push(type); - values.push(mbtiData[type]); - colors.push(colorPalette.mbti[colorIndex % colorPalette.mbti.length]); - colorIndex++; - } - }); - - // Si no hay datos, no mostrar ningún dato de ejemplo - if (labels.length === 0) { - // No hay estudiantes que hayan realizado el test - no mostrar datos - document.getElementById('mbtiChart').parentNode.innerHTML = - '
' + - strings.sin_datos_estudiantes + '
'; - return; - } - - new Chart(ctx, { - type: "pie", - data: { - labels: labels, - datasets: [{ - data: values, - backgroundColor: colors, - borderColor: "#ffffff", - borderWidth: 1, - hoverBorderWidth: 2, - hoverBorderColor: "#ffffff" - }] - }, - options: { - responsive: true, - maintainAspectRatio: true, - plugins: { - title: { - display: true, - text: strings.titulo_distribucion_mbti, - font: { - family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - size: 14, - weight: "bold" - }, - padding: { - top: 10, - bottom: 20 - } - }, - legend: { - position: "top", - labels: { - font: { - family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - size: 12 - }, - padding: 15 - } - }, - tooltip: { - backgroundColor: "rgba(0, 43, 73, 0.8)", - titleFont: { - size: 13 - }, - bodyFont: { - size: 13 - }, - padding: 10, - cornerRadius: 5, - callbacks: { - label: function(context) { - var label = context.label || ""; - if (label) { - label += ": "; - } - if (context.parsed !== null) { - var total = context.chart.data.datasets[0].data.reduce(function(a, b) { - return a + b; - }, 0); - var percentage = Math.round((context.parsed / total) * 100); - label += context.parsed + " (" + percentage + "%)"; - } - return label; - } - } - } - } - } - }); - } - } - - function createBarChart(elementId, title, labels, data, colors, indexAxis) { - var ctx = document.getElementById(elementId); - if (ctx) { - // Constrain height in wide Moodle layouts (sidebars, large screens) - try { - ctx.style.maxHeight = "320px"; - if (ctx.parentNode && ctx.parentNode.style) { - ctx.parentNode.style.maxHeight = "320px"; - ctx.parentNode.style.position = "relative"; - } - } catch (e) {} - - ctx = ctx.getContext("2d"); - - // Verificar si tenemos datos, pero no usar datos de ejemplo si no hay - if (!data || !data.length || (data[0] === 0 && data[1] === 0)) { - // No hay estudiantes que hayan realizado el test - no mostrar datos - document.getElementById(elementId).parentNode.innerHTML = - '
' + - strings.sin_datos_estudiantes + '
'; - return; - } - - var maxValue = Math.max.apply(null, data); - var yMax = Math.ceil(maxValue * 1.1); - - if (!indexAxis) { - var hasLongLabels = Array.isArray(labels) && labels.some(function(l) { - return (l || "").length > 12; - }); - var isMobile = window.matchMedia && window.matchMedia("(max-width: 576px)").matches; - indexAxis = (isMobile && hasLongLabels) ? "y" : "x"; - } - - var valueAxis = (indexAxis === "y") ? "x" : "y"; - var categoryAxis = (indexAxis === "y") ? "y" : "x"; - - function adjustColor(color, percent) { - var r = parseInt(color.substring(1, 3), 16); - var g = parseInt(color.substring(3, 5), 16); - var b = parseInt(color.substring(5, 7), 16); - - r = parseInt(r * (100 + percent) / 100); - g = parseInt(g * (100 + percent) / 100); - b = parseInt(b * (100 + percent) / 100); - - r = (r < 255) ? r : 255; - g = (g < 255) ? g : 255; - b = (b < 255) ? b : 255; - - r = Math.max(0, r); - g = Math.max(0, g); - b = Math.max(0, b); - - var rr = ((r.toString(16).length == 1) ? "0" + r.toString(16) : r.toString(16)); - var gg = ((g.toString(16).length == 1) ? "0" + g.toString(16) : g.toString(16)); - var bb = ((b.toString(16).length == 1) ? "0" + b.toString(16) : b.toString(16)); - - return "#" + rr + gg + bb; - } - - var borderColors = []; - var hoverBgColors = []; - var hoverBorderColors = []; - - for (var i = 0; i < colors.length; i++) { - borderColors.push(adjustColor(colors[i], -20)); - hoverBgColors.push(adjustColor(colors[i], 10)); - hoverBorderColors.push(adjustColor(colors[i], -30)); - } - - new Chart(ctx, { - type: "bar", - data: { - labels: labels, - datasets: [{ - label: strings.num_estudiantes_header, - data: data, - backgroundColor: colors, - borderColor: borderColors, - borderWidth: 1, - borderRadius: 3, - hoverBackgroundColor: hoverBgColors, - hoverBorderColor: hoverBorderColors, - barPercentage: 0.6, - categoryPercentage: 0.8 - }] - }, - options: { - responsive: true, - maintainAspectRatio: true, - indexAxis: indexAxis, - animation: { - duration: 1500, - easing: "easeOutQuart" - }, - layout: { - padding: { - top: 5, - right: 10, - bottom: 5, - left: 10 - } - }, - scales: ((obj = {}, obj[valueAxis] = { - beginAtZero: true, - ticks: { - stepSize: 1, - precision: 0, - font: { - size: 11 - } - }, - max: yMax, - grid: { - color: "rgba(0, 43, 73, 0.05)", - lineWidth: 1 - } - }, obj[categoryAxis] = { - grid: { - display: false - }, - ticks: { - font: { - size: 11 - } - } - }, obj)), - plugins: { - title: { - display: true, - text: title, - font: { - family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - size: 14, - weight: "bold" - }, - padding: { - top: 10, - bottom: 20 - } - }, - legend: { - display: false - }, - tooltip: { - backgroundColor: "rgba(0, 43, 73, 0.8)", - titleFont: { - size: 13 - }, - bodyFont: { - size: 13 - }, - padding: 10, - cornerRadius: 5, - callbacks: { - label: function(context) { - var v = (indexAxis === "y") ? context.parsed.x : context.parsed.y; - return strings.num_estudiantes_header + ": " + v; - }, - title: function(context) { - return context[0].label; - } - } - } - } - } - }); - } - } - - // Crear las gráficas - createMBTIChart(); - - createBarChart( - "generalTrendChart", - strings.introversion_extroversion, - [strings.Introvertido, strings.Extrovertido], - [aspectData.Introvertido || 0, aspectData.Extrovertido || 0], - colorPalette.introversion - ); - - createBarChart( - "infoProcessingChart", - strings.sensacion_intuicion, - [strings.Sensing, strings.Intuicion], - [aspectData.Sensing || 0, aspectData.Intuición || 0], - colorPalette.sensacion - ); - - createBarChart( - "decisionMakingChart", - strings.pensamiento_sentimiento, - [strings.Pensamiento, strings.Sentimiento], - [aspectData.Pensamiento || 0, aspectData.Sentimiento || 0], - colorPalette.pensamiento - ); - - createBarChart( - "organizationChart", - strings.juicio_percepcion, - [strings.Juicio, strings.Percepcion], - [aspectData.Juicio || 0, aspectData.Percepción || 0], - colorPalette.juicio - ); - } - }; -}); +define(["core/chartjs"],(function(t){return{init:function(e,i,n){var r={mbti:["#005B9A","#FF8200","#FFB600","#00B5E2","#78BE20","#2C5234","#652C8F","#91268F","#D0006F","#AA182C","#8B0304","#E35205","#385CAD","#0077C8","#00263A","#00A9B7"],introversion:["#005B9A","#FF8200"],sensacion:["#00B5E2","#FFB600"],pensamiento:["#78BE20","#652C8F"],juicio:["#AA182C","#0077C8"]};function a(e,i,r,a,o,s){var d=document.getElementById(e);if(d){try{d.style.maxHeight="320px",d.parentNode&&d.parentNode.style&&(d.parentNode.style.maxHeight="320px",d.parentNode.style.position="relative")}catch(x){}if(d=d.getContext("2d"),!a||!a.length||0===a[0]&&0===a[1])return void(document.getElementById(e).parentNode.innerHTML='
'+n.sin_datos_estudiantes+"
");var l=Math.max.apply(null,a),c=Math.ceil(1.1*l);if(!s){var p=Array.isArray(r)&&r.some((function(t){return(t||"").length>12})),u=window.matchMedia&&window.matchMedia("(max-width: 576px)").matches;s=u&&p?"y":"x"}var g="y"===s?"x":"y",h="y"===s?"y":"x";function f(t,e){var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),r=parseInt(t.substring(5,7),16);return i=(i=parseInt(i*(100+e)/100))<255?i:255,n=(n=parseInt(n*(100+e)/100))<255?n:255,r=(r=parseInt(r*(100+e)/100))<255?r:255,i=Math.max(0,i),n=Math.max(0,n),r=Math.max(0,r),"#"+(1==i.toString(16).length?"0"+i.toString(16):i.toString(16))+(1==n.toString(16).length?"0"+n.toString(16):n.toString(16))+(1==r.toString(16).length?"0"+r.toString(16):r.toString(16))}for(var b=[],m=[],v=[],y=0;y0&&(a.push(t),o.push(e[t]),s.push(r.mbti[d%r.mbti.length]),d++)})),0===a.length)return void(document.getElementById("mbtiChart").parentNode.innerHTML='
'+n.sin_datos_estudiantes+"
");new t(i,{type:"pie",data:{labels:a,datasets:[{data:o,backgroundColor:s,borderColor:"#ffffff",borderWidth:1,hoverBorderWidth:2,hoverBorderColor:"#ffffff"}]},options:{responsive:!0,maintainAspectRatio:!0,plugins:{title:{display:!0,text:n.titulo_distribucion_mbti,font:{family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:14,weight:"bold"},padding:{top:10,bottom:20}},legend:{position:"top",labels:{font:{family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12},padding:15}},tooltip:{backgroundColor:"rgba(0, 43, 73, 0.8)",titleFont:{size:13},bodyFont:{size:13},padding:10,cornerRadius:5,callbacks:{label:function(t){var e=t.label||"";if(e&&(e+=": "),null!==t.parsed){var i=t.chart.data.datasets[0].data.reduce((function(t,e){return t+e}),0),n=Math.round(t.parsed/i*100);e+=t.parsed+" ("+n+"%)"}return e}}}}}})}}(),a("generalTrendChart",n.introversion_extroversion,[n.Introvertido,n.Extrovertido],[i.Introvertido||0,i.Extrovertido||0],r.introversion),a("infoProcessingChart",n.sensacion_intuicion,[n.Sensing,n.Intuicion],[i.Sensing||0,i.Intuición||0],r.sensacion),a("decisionMakingChart",n.pensamiento_sentimiento,[n.Pensamiento,n.Sentimiento],[i.Pensamiento||0,i.Sentimiento||0],r.pensamiento),a("organizationChart",n.juicio_percepcion,[n.Juicio,n.Percepcion],[i.Juicio||0,i.Percepción||0],r.juicio)}}})); diff --git a/amd/build/results_radar.min.js b/amd/build/results_radar.min.js new file mode 100644 index 0000000..5bd4911 --- /dev/null +++ b/amd/build/results_radar.min.js @@ -0,0 +1 @@ +define(["core/chartjs"],(function(r){return{init:function(o,n,t,a){var e=document.getElementById(o);if(e){var i=e.getContext("2d");new r(i,{type:"radar",data:{labels:n,datasets:[{label:a,data:t,backgroundColor:"rgba(0, 191, 145, 0.2)",borderColor:"rgba(0, 191, 145, 1)",pointBackgroundColor:"rgba(0, 191, 145, 1)",pointBorderColor:"#fff",pointHoverBackgroundColor:"#fff",pointHoverBorderColor:"rgba(0, 191, 145, 1)"}]},options:{scales:{r:{beginAtZero:!0,min:0,max:9,angleLines:{display:!0,color:"rgba(0, 0, 0, 0.1)"},grid:{color:function(r){return r.tick.value%2==1?"transparent":"rgba(0, 0, 0, 0.1)"},lineWidth:1},ticks:{stepSize:1,display:!0,backdropColor:"transparent",callback:function(r){return r%2!=0?r:""},font:{size:12}},pointLabels:{font:{size:14}}}}}})}}}})); diff --git a/amd/src/results_radar.js b/amd/src/results_radar.js new file mode 100644 index 0000000..58215c9 --- /dev/null +++ b/amd/src/results_radar.js @@ -0,0 +1,62 @@ +define(['core/chartjs'], function(Chart) { + return { + init: function(chartId, labels, data, datasetLabel) { + var el = document.getElementById(chartId); + if(!el) return; + var ctx = el.getContext('2d'); + + return new Chart(ctx, { + type: 'radar', + data: { + labels: labels, + datasets: [{ + label: datasetLabel, + data: data, + backgroundColor: 'rgba(0, 191, 145, 0.2)', + borderColor: 'rgba(0, 191, 145, 1)', + pointBackgroundColor: 'rgba(0, 191, 145, 1)', + pointBorderColor: '#fff', + pointHoverBackgroundColor: '#fff', + pointHoverBorderColor: 'rgba(0, 191, 145, 1)' + }] + }, + options: { + scales: { + r: { + beginAtZero: true, + min: 0, + max: 9, + angleLines: { + display: true, + color: 'rgba(0, 0, 0, 0.1)' + }, + grid: { + color: function(context) { + if (context.tick.value % 2 === 1) { + return 'transparent'; + } + return 'rgba(0, 0, 0, 0.1)'; + }, + lineWidth: 1 + }, + ticks: { + stepSize: 1, + display: true, + backdropColor: 'transparent', + callback: function(value) { + return value % 2 !== 0 ? value : ''; + }, + font: { + size: 12 + } + }, + pointLabels: { + font: {size: 14} + } + } + } + } + }); + } + }; +}); diff --git a/block_personality_test.php b/block_personality_test.php index 1546952..675deba 100644 --- a/block_personality_test.php +++ b/block_personality_test.php @@ -1,4 +1,12 @@ '; - $slider .= $izq_val . " ↹ " . $der_val . "
"; - $slider .= ''; - $slider .= ''; - return $slider; - } - function init() { $this->title = get_string('pluginname', 'block_personality_test'); @@ -79,9 +76,6 @@ function instance_allow_multiple() return false; } - - // Función para la vista del Profesor - /** * Genera el contenido para la vista del profesor. * @@ -90,21 +84,12 @@ function instance_allow_multiple() * @return stdClass Un objeto con las propiedades 'text' y 'footer' para el contenido del bloque. */ private function _get_teacher_content($DB, $COURSE) { - // Necesitamos $OUTPUT global aquí para moodle_url si se usa directamente o para get_string global $OUTPUT; $content = new stdClass(); $content->text = ''; $content->footer = ''; - // Header with personality test icon for teacher/admin view. - $content->text .= '
'; - $content->text .= $this->get_personality_test_icon('4em', '', true); - $content->text .= '
' . get_string('management_title', 'block_personality_test') . '
'; - $content->text .= '' . get_string('course_overview', 'block_personality_test') . ''; - $content->text .= '
'; - - // --- Vista del Profesor --- // Obtener usuarios inscritos que pueden realizar el test (por defecto: estudiantes) $context = context_course::instance($COURSE->id); $enrolled_students = get_enrolled_users($context, 'block/personality_test:taketest', 0, 'u.id', null, 0, 0, true); @@ -123,353 +108,84 @@ private function _get_teacher_content($DB, $COURSE) { $filtered_student_ids[] = $candidateid; } $student_ids = $filtered_student_ids; + $total_students = count($student_ids); // Obtener respuestas solo de estudiantes inscritos que hayan COMPLETADO el test $students = array(); if (!empty($student_ids)) { list($insql, $params) = $DB->get_in_or_equal($student_ids, SQL_PARAMS_NAMED, 'user'); $params['completed'] = 1; - $sql = "SELECT * FROM {personality_test} WHERE user $insql AND is_completed = :completed"; + // OPTIMIZATION: Only fetch necessary columns, avoid fetching all 72 question columns + $sql = "SELECT id, user, extraversion, introversion, sensing, intuition, thinking, feeling, judging, perceptive + FROM {personality_test} WHERE user $insql AND is_completed = :completed"; $students = $DB->get_records_sql($sql, $params); } + $has_data = !empty($students); + $in_progress = 0; + // Si no hay tests completados, mostrar estadísticas básicas - if(empty($students)) { + if(!$has_data) { // Contar tests en progreso - $in_progress = 0; if (!empty($student_ids)) { list($insql, $params) = $DB->get_in_or_equal($student_ids, SQL_PARAMS_NAMED, 'user'); $params['completed'] = 0; $in_progress = $DB->count_records_select('personality_test', "user $insql AND is_completed = :completed", $params); } - - $total_students = count($student_ids); - - $content->text .= '
'; - $content->text .= '
' . get_string('participation_stats', 'block_personality_test') . '
'; - $content->text .= ''; - $content->text .= '
'; - $content->text .= '

' . get_string('sin_datos_estudiantes', 'block_personality_test') . '

'; - $content->text .= '

' . get_string('waiting_first_completion', 'block_personality_test') . '

'; - $content->text .= '
'; - return $content; } - $mbti_types = ["ISTJ", "ISFJ", "INFJ", "INTJ", "ISTP", "ISFP", "INFP", "INTP", "ESTP", "ESFP", "ENFP", "ENTP", "ESTJ", "ESFJ", "ENFJ", "ENTJ"]; - $mbti_count = array_fill_keys($mbti_types, 0); - - $aspect_counts = [ - "Introvertido" => 0, "Extrovertido" => 0, - "Sensing" => 0, "Intuición" => 0, - "Pensamiento" => 0, "Sentimiento" => 0, - "Juicio" => 0, "Percepción" => 0 + $template_data = [ + 'icon' => $this->get_personality_test_icon('4em', '', true), + 'has_data' => $has_data, + 'total_students' => $total_students, + 'in_progress' => $in_progress, ]; - foreach ($students as $entry) { - if (!isset($entry->extraversion, $entry->introversion, $entry->sensing, $entry->intuition, $entry->thinking, $entry->feeling, $entry->judging, $entry->perceptive)) { - continue; - } - - $mbti_score = ""; - $mbti_score .= ($entry->extraversion > $entry->introversion) ? "E" : "I"; - $mbti_score .= ($entry->sensing > $entry->intuition) ? "S" : "N"; - $mbti_score .= ($entry->thinking >= $entry->feeling) ? "T" : "F"; - $mbti_score .= ($entry->judging > $entry->perceptive) ? "J" : "P"; - - if (isset($mbti_count[$mbti_score])) { - $mbti_count[$mbti_score]++; - } - - $aspect_counts["Introvertido"] += ($entry->introversion >= $entry->extraversion) ? 1 : 0; - $aspect_counts["Extrovertido"] += ($entry->extraversion > $entry->introversion) ? 1 : 0; - $aspect_counts["Sensing"] += ($entry->sensing > $entry->intuition) ? 1 : 0; - $aspect_counts["Intuición"] += ($entry->intuition >= $entry->sensing) ? 1 : 0; - $aspect_counts["Pensamiento"] += ($entry->thinking >= $entry->feeling) ? 1 : 0; - $aspect_counts["Sentimiento"] += ($entry->feeling > $entry->thinking) ? 1 : 0; - $aspect_counts["Juicio"] += ($entry->judging > $entry->perceptive) ? 1 : 0; - $aspect_counts["Percepción"] += ($entry->perceptive >= $entry->judging) ? 1 : 0; - } - - $mbti_json = json_encode(array_filter($mbti_count)); - $aspects_json = json_encode($aspect_counts); - - $str_titulo_distribucion_mbti = json_encode(get_string('titulo_distribucion_mbti', 'block_personality_test')); - $str_num_estudiantes = json_encode(get_string('num_estudiantes', 'block_personality_test')); - $str_introversion_extroversion = json_encode(get_string('introversion_extroversion', 'block_personality_test')); - $str_sensacion_intuicion = json_encode(get_string('sensacion_intuicion', 'block_personality_test')); - $str_pensamiento_sentimiento = json_encode(get_string('pensamiento_sentimiento', 'block_personality_test')); - $str_juicio_percepcion = json_encode(get_string('juicio_percepcion', 'block_personality_test')); - - // Mostrar estadísticas de participación - $total_enrolled = count($student_ids); - $total_completed = count($students); - $completion_percentage = $total_enrolled > 0 ? round(($total_completed / $total_enrolled) * 100, 1) : 0; - - $participation_data = new stdClass(); - $participation_data->completed = $total_completed; - $participation_data->total = $total_enrolled; - $participation_data->percentage = $completion_percentage; - - $content->text .= html_writer::start_div('alert alert-info', ['style' => 'margin-bottom: 15px; padding: 10px; text-align: center;']); - $content->text .= html_writer::tag('strong', get_string('participation_stats', 'block_personality_test') . ': '); - $content->text .= html_writer::tag('span', get_string('students_completed_test', 'block_personality_test', $participation_data)); - $content->text .= html_writer::end_div(); - - $content->text .= html_writer::tag('h6',get_string('titulo_resultados_estudiantes', 'block_personality_test'),['style' => 'text-align: center;']); - $content->text .= html_writer::tag('canvas', '', ['id' => 'mbtiChart', 'style' => 'max-width: 100%; max-height: 350px; height: auto;']); $content->text .= html_writer::tag('h6', get_string('titulo_distribucion_rasgos', 'block_personality_test'), ['style' => 'text-align: center; margin-top: 20px;']); - - $content->text .= html_writer::start_div('d-flex flex-wrap justify-content-around'); - $chart_style = "width: 100%; max-width: 350px; margin: 10px; box-sizing: border-box;"; - $content->text .= html_writer::div(html_writer::tag('canvas', '', ['id' => 'generalTrendChart']), '', ['style' => $chart_style]); - $content->text .= html_writer::div(html_writer::tag('canvas', '', ['id' => 'infoProcessingChart']), '', ['style' => $chart_style]); - $content->text .= html_writer::div(html_writer::tag('canvas', '', ['id' => 'decisionMakingChart']), '', ['style' => $chart_style]); - $content->text .= html_writer::div(html_writer::tag('canvas', '', ['id' => 'organizationChart']), '', ['style' => $chart_style]); - $content->text .= html_writer::end_div(); - - // Preparar datos para JavaScript - $strings = array( - 'titulo_distribucion_mbti' => get_string('titulo_distribucion_mbti', 'block_personality_test'), - 'num_estudiantes_header' => get_string('num_estudiantes_header', 'block_personality_test'), - 'introversion_extroversion' => get_string('introversion_extroversion', 'block_personality_test'), - 'sensacion_intuicion' => get_string('sensacion_intuicion', 'block_personality_test'), - 'pensamiento_sentimiento' => get_string('pensamiento_sentimiento', 'block_personality_test'), - 'juicio_percepcion' => get_string('juicio_percepcion', 'block_personality_test'), - 'Introvertido' => get_string('Introvertido', 'block_personality_test'), - 'Extrovertido' => get_string('Extrovertido', 'block_personality_test'), - 'Sensing' => get_string('Sensing', 'block_personality_test'), - 'Intuicion' => get_string('Intuicion', 'block_personality_test'), - 'Pensamiento' => get_string('Pensamiento', 'block_personality_test'), - 'Sentimiento' => get_string('Sentimiento', 'block_personality_test'), - 'Juicio' => get_string('Juicio', 'block_personality_test'), - 'Percepcion' => get_string('Percepcion', 'block_personality_test'), - 'sin_datos_estudiantes' => get_string('sin_datos_estudiantes', 'block_personality_test') - ); - - $js_code = " - require(['core/chartjs'], function(Chart) { - var mbtiData = " . $mbti_json . "; - var aspectData = " . json_encode($aspect_counts) . "; - var strings = " . json_encode($strings) . "; - - // Paleta de colores SAVIO UTB - const colorPalette = { - mbti: [ - '#005B9A', '#FF8200', '#FFB600', '#00B5E2', - '#78BE20', '#2C5234', '#652C8F', '#91268F', - '#D0006F', '#AA182C', '#8B0304', '#E35205', - '#385CAD', '#0077C8', '#00263A', '#00A9B7' - ], - introversion: ['#005B9A', '#FF8200'], - sensacion: ['#00B5E2', '#FFB600'], - pensamiento: ['#78BE20', '#652C8F'], - juicio: ['#AA182C', '#0077C8'] - }; - - // Función para crear gráfico de pie MBTI - function createMBTIChart() { - var ctxPie = document.getElementById('mbtiChart'); - if (ctxPie) { - ctxPie = ctxPie.getContext('2d'); - - const mbtiLabels = []; - const mbtiValues = []; - const mbtiColors = []; - - let colorIndex = 0; - if (typeof mbtiData === 'string') { - try { mbtiData = JSON.parse(mbtiData); } catch (e) {} - } - - Object.keys(mbtiData).forEach(key => { - if (mbtiData[key] > 0) { - mbtiLabels.push(key); - mbtiValues.push(mbtiData[key]); - mbtiColors.push(colorPalette.mbti[colorIndex % colorPalette.mbti.length]); - colorIndex++; - } - }); - - if (mbtiLabels.length === 0) { - document.getElementById('mbtiChart').parentNode.innerHTML = - '
' + - strings.sin_datos_estudiantes + '
'; - return; - } - - new Chart(ctxPie, { - type: 'pie', - data: { - labels: mbtiLabels, - datasets: [{ - data: mbtiValues, - backgroundColor: mbtiColors, - borderColor: '#ffffff', - borderWidth: 1, - hoverOffset: 4 - }] - }, - options: { - responsive: true, - maintainAspectRatio: true, - plugins: { - title: { - display: true, - text: strings.titulo_distribucion_mbti, - font: { size: 14, weight: '500' }, - padding: { top: 5, bottom: 15 } - }, - legend: { - position: 'top', - labels: { boxWidth: 15, padding: 8, font: { size: 11 } } - }, - tooltip: { - backgroundColor: 'rgba(0, 43, 73, 0.8)', - callbacks: { - label: function(context) { - let label = context.label || ''; - if (label) { label += ': '; } - if (context.parsed !== null) { - let total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0); - let percentage = Math.round((context.parsed / total) * 100); - label += context.parsed + ' (' + percentage + '%)'; - } - return label; - } - } - } - } - } - }); - } - } - - // Función para crear gráficos de barras - function createBarChart(elementId, title, labels, data, colors) { - var ctx = document.getElementById(elementId); - if (ctx) { - ctx = ctx.getContext('2d'); - - if (!data || !data.length || (data[0] === 0 && data[1] === 0)) { - document.getElementById(elementId).parentNode.innerHTML = - '
' + - strings.sin_datos_estudiantes + '
'; - return; - } - - const maxValue = Math.max(...data); - const yMax = Math.ceil(maxValue * 1.1); - - new Chart(ctx, { - type: 'bar', - data: { - labels: labels, - datasets: [{ - label: strings.num_estudiantes_header, - data: data, - backgroundColor: colors, - borderColor: colors, - borderWidth: 0, - borderRadius: 2, - barPercentage: 0.8, - categoryPercentage: 0.9 - }] - }, - options: { - responsive: true, - maintainAspectRatio: true, - indexAxis: 'x', - scales: { - y: { - beginAtZero: true, - max: yMax, - ticks: { stepSize: 1, precision: 0, font: { size: 11 } }, - grid: { color: 'rgba(0, 43, 73, 0.05)', drawBorder: false } - }, - x: { - grid: { display: false, drawBorder: false }, - ticks: { font: { size: 11 } } - } - }, - plugins: { - title: { - display: true, - text: title, - font: { size: 14, weight: '500' }, - padding: { top: 5, bottom: 15 } - }, - legend: { display: false }, - tooltip: { - backgroundColor: 'rgba(0, 43, 73, 0.8)', - callbacks: { - label: function(context) { - return strings.num_estudiantes_header + ': ' + context.parsed.y; - } - } - } - } - } - }); - } - } - - // Crear todas las gráficas - createMBTIChart(); - - createBarChart( - 'generalTrendChart', - strings.introversion_extroversion, - [strings.Introvertido, strings.Extrovertido], - [aspectData.Introvertido || 0, aspectData.Extrovertido || 0], - colorPalette.introversion - ); - - createBarChart( - 'infoProcessingChart', - strings.sensacion_intuicion, - [strings.Sensing, strings.Intuicion], - [aspectData.Sensing || 0, aspectData.Intuición || 0], - colorPalette.sensacion + if ($has_data) { + $mbti_count = PersonalityTestFacade::get_mbti_counts($students); + $aspect_counts = PersonalityTestFacade::get_aspect_counts($students); + + // Preparar datos para JavaScript + $header_strings = array( + 'titulo_distribucion_mbti' => get_string('titulo_distribucion_mbti', 'block_personality_test'), + 'num_estudiantes_header' => get_string('num_estudiantes_header', 'block_personality_test'), + 'introversion_extroversion' => get_string('introversion_extroversion', 'block_personality_test'), + 'sensacion_intuicion' => get_string('sensacion_intuicion', 'block_personality_test'), + 'pensamiento_sentimiento' => get_string('pensamiento_sentimiento', 'block_personality_test'), + 'juicio_percepcion' => get_string('juicio_percepcion', 'block_personality_test'), + 'Introvertido' => get_string('Introvertido', 'block_personality_test'), + 'Extrovertido' => get_string('Extrovertido', 'block_personality_test'), + 'Sensing' => get_string('Sensing', 'block_personality_test'), + 'Intuicion' => get_string('Intuicion', 'block_personality_test'), + 'Pensamiento' => get_string('Pensamiento', 'block_personality_test'), + 'Sentimiento' => get_string('Sentimiento', 'block_personality_test'), + 'Juicio' => get_string('Juicio', 'block_personality_test'), + 'Percepcion' => get_string('Percepcion', 'block_personality_test'), + 'sin_datos_estudiantes' => get_string('sin_datos_estudiantes', 'block_personality_test') ); - createBarChart( - 'decisionMakingChart', - strings.pensamiento_sentimiento, - [strings.Pensamiento, strings.Sentimiento], - [aspectData.Pensamiento || 0, aspectData.Sentimiento || 0], - colorPalette.pensamiento - ); - - createBarChart( - 'organizationChart', - strings.juicio_percepcion, - [strings.Juicio, strings.Percepcion], - [aspectData.Juicio || 0, aspectData.Percepción || 0], - colorPalette.juicio - ); - }); - "; + // Mostrar estadísticas de participación + $total_completed = count($students); + $completion_percentage = $total_students > 0 ? round(($total_completed / $total_students) * 100, 1) : 0; + + $participation_data = new stdClass(); + $participation_data->completed = $total_completed; + $participation_data->total = $total_students; + $participation_data->percentage = $completion_percentage; + + $template_data['completed_str'] = get_string('students_completed_test', 'block_personality_test', $participation_data); + $template_data['csv_url'] = (new moodle_url('/blocks/personality_test/download_csv.php', ['courseid' => $COURSE->id, 'sesskey' => sesskey()]))->out(false); + $template_data['pdf_url'] = (new moodle_url('/blocks/personality_test/download_pdf.php', ['courseid' => $COURSE->id, 'sesskey' => sesskey()]))->out(false); + + // Call AMD module + $this->page->requires->js_call_amd('block_personality_test/charts', 'init', [ + array_filter($mbti_count), + $aspect_counts, + $header_strings + ]); + } - $this->page->requires->js_init_code($js_code); - - $csv_url = new moodle_url('/blocks/personality_test/download_csv.php', ['courseid' => $COURSE->id, 'sesskey' => sesskey()]); - $pdf_url = new moodle_url('/blocks/personality_test/download_pdf.php', ['courseid' => $COURSE->id, 'sesskey' => sesskey()]); - - $download_links = html_writer::start_div('text-center', ['style' => 'margin-top: 20px;']); - $link_attributes = [ - 'class' => 'btn btn-sm d-inline-block', - 'style' => 'margin: 5px; background-color: #1e7e34; color: #ffffff; text-decoration: none; border: none;', - 'role' => 'button' - ]; - $download_links .= html_writer::link($csv_url, get_string('CSV', 'block_personality_test'), $link_attributes); - $download_links .= html_writer::link($pdf_url, get_string('PDF', 'block_personality_test'), $link_attributes); - $download_links .= html_writer::end_div(); - - $content->text .= $download_links; - $content->footer = ''; + $content->text = $OUTPUT->render_from_template('block_personality_test/teacher_dashboard', $template_data); return $content; } @@ -481,7 +197,7 @@ function createBarChart(elementId, title, labels, data, colors) { * @return string HTML img tag with the SVG icon */ private function get_personality_test_icon($size = '1.8em', $additional_style = '', $centered = false) { - $iconurl = new moodle_url('/blocks/personality_test/pix/personality_test_icon.svg'); + $iconurl = new moodle_url('/blocks/personality_test/pix/icon.svg'); $style = 'width: ' . $size . '; height: ' . $size . '; vertical-align: middle; float: none !important;'; if ($centered) { $style .= ' display: block; margin: 0 auto;'; @@ -496,130 +212,45 @@ private function get_personality_test_icon($size = '1.8em', $additional_style = * Método para mostrar la invitación al test de personalidad */ private function get_test_invitation() { - global $COURSE; - - $output = ''; - $output .= '
'; + global $COURSE, $OUTPUT; - // Header with personality test icon - $output .= '
'; - $output .= $this->get_personality_test_icon('4em', '', true); - $output .= '
' . get_string('test_title', 'block_personality_test') . '
'; - $output .= '' . get_string('discover_your_personality', 'block_personality_test') . ''; - $output .= '
'; - - // Test description card - $output .= '
'; - $output .= '
'; - $output .= '
'; - $output .= '
'; - $output .= ' '; - $output .= get_string('what_is_mbti', 'block_personality_test'); - $output .= '
'; - $output .= '

' . get_string('test_description', 'block_personality_test') . '

'; - $output .= '
    '; - $output .= '
  • ' . get_string('feature_72_questions', 'block_personality_test') . '
  • '; - $output .= '
  • ' . get_string('feature_16_types', 'block_personality_test') . '
  • '; - $output .= '
  • ' . get_string('feature_instant_results', 'block_personality_test') . '
  • '; - $output .= '
'; - $output .= '
'; - $output .= '
'; - $output .= '
'; - - // Action button - $output .= '
'; $url = new moodle_url('/blocks/personality_test/view.php', array('cid' => $COURSE->id)); - $output .= ''; - $output .= ' ' . get_string('start_test', 'block_personality_test') . ''; - $output .= ''; - $output .= '
'; - - $output .= '
'; + $data = [ + 'icon' => $this->get_personality_test_icon('4em', '', true), + 'url' => $url->out(false) + ]; - return $output; + return $OUTPUT->render_from_template('block_personality_test/student_invitation', $data); } /** * Display continue test card for students with test in progress - * Design matches learning_style block for consistency */ private function get_continue_test_card($answered_count) { - global $COURSE; + global $COURSE, $OUTPUT; - $output = ''; $progress_percentage = ($answered_count / 72) * 100; $all_answered = ($answered_count >= 72); - $output .= '
'; - - // Header with personality test icon - $output .= '
'; - $output .= $this->get_personality_test_icon('4em', 'text-shadow: 0 1px 2px rgba(0,0,0,0.1);', true); - $output .= '
' . get_string('test_title', 'block_personality_test') . '
'; - $output .= '' . get_string('discover_your_personality', 'block_personality_test') . ''; - $output .= '
'; - - // Description section - $output .= '
'; - $output .= ''; - $output .= ' '; - $output .= get_string('test_description', 'block_personality_test'); - $output .= ''; - $output .= '
'; - - // Special alert if all questions answered but not submitted - if ($all_answered) { - $output .= '
'; - $output .= '
'; - $output .= ''; - $output .= '
'; - $output .= '' . get_string('all_answered_title', 'block_personality_test') . '
'; - $output .= '' . get_string('all_answered_message', 'block_personality_test') . ''; - $output .= '
'; - $output .= '
'; - $output .= '
'; - } - - // Progress section - $output .= '
'; - $output .= '
'; - $output .= '' . get_string('your_progress', 'block_personality_test') . ''; - $output .= '' . $answered_count . '/72'; - $output .= '
'; - $output .= '
'; - $output .= '
'; - $output .= '
'; - $output .= '' . number_format($progress_percentage, 1) . '% ' . get_string('completed', 'block_personality_test') . ''; - $output .= '
'; - - // Call to action button - $output .= '
'; - + $url_params = ['cid' => $COURSE->id]; if ($all_answered) { - // Go to last page (8) with scroll parameter for finish button - $url = new moodle_url('/blocks/personality_test/view.php', array('cid' => $COURSE->id, 'page' => 8, 'scroll_to_finish' => 1)); - $output .= ''; - $output .= ' ' . get_string('finish_test_now', 'block_personality_test'); - $output .= ''; - } else { - // Go to page with first unanswered question - $url = new moodle_url('/blocks/personality_test/view.php', array('cid' => $COURSE->id)); - $output .= ''; - $output .= ' ' . get_string('continue_test', 'block_personality_test'); - $output .= ''; + $url_params['page'] = 8; + $url_params['scroll_to_finish'] = 1; } + $url = new moodle_url('/blocks/personality_test/view.php', $url_params); + + $data = [ + 'icon' => $this->get_personality_test_icon('4em', 'text-shadow: 0 1px 2px rgba(0,0,0,0.1);', true), + 'answered_count' => $answered_count, + 'progress_percentage' => $progress_percentage, + 'progress_percentage_formatted' => number_format($progress_percentage, 1), + 'all_answered' => $all_answered, + 'url' => $url->out(false) + ]; - $output .= '
'; - - $output .= '
'; - - return $output; + return $OUTPUT->render_from_template('block_personality_test/student_continue', $data); } - // Función para la vista del Profesor - - - function get_content() { // Declarar globales necesarios @@ -628,8 +259,8 @@ function get_content() // --- Validaciones Iniciales --- // No mostrar en la página principal del sitio if ($COURSE->id == SITEID) { - $this->content = new stdClass; $this->content->text = ''; $this->content->footer = ''; // Necesario inicializar para evitar error - return $this->content; // Devolver objeto vacío en lugar de nada + $this->content = new stdClass; $this->content->text = ''; $this->content->footer = ''; + return $this->content; } // Si el contenido ya se generó, devolverlo @@ -642,17 +273,12 @@ function get_content() $this->content->text = ''; $this->content->footer = ''; - // Si la instancia del bloque no está configurada (?) if (empty($this->instance)) { - // Podría mostrar un error o mensaje aquí si fuera necesario return $this->content; } - // Si el usuario no está logueado if (!isloggedin()) { - // No se devuelve nada explícitamente, pero el contenido estará vacío. - // Considera añadir un mensaje como: $this->content->text = get_string('logintoview'); - return $this->content; // Devolver objeto vacío + return $this->content; } // --- Lógica Principal --- @@ -663,7 +289,8 @@ function get_content() if (has_capability('block/personality_test:viewreports', $context)) { $teacher_content = $this->_get_teacher_content($DB, $COURSE); $this->content = $teacher_content; - // Agregar enlace a la vista administrativa en el footer para consistencia + + // Agregar enlace a la vista administrativa $admin_url = new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $COURSE->id)); $this->content->footer .= html_writer::div( html_writer::link($admin_url, @@ -677,9 +304,7 @@ function get_content() // Si el usuario puede realizar el test, mostrar la vista del estudiante. if (has_capability('block/personality_test:taketest', $context)) { - // --- LÓGICA PARA EL ESTUDIANTE --- - - // Verificar si el estudiante ya tiene una entrada en la tabla (en cualquier curso) + // Verificar si el estudiante ya tiene una entrada en la tabla $entry = $DB->get_record('personality_test', array('user' => $USER->id)); if (!$entry) { @@ -714,42 +339,6 @@ function get_content() $mbti_score .= ($scores["thinking"] >= $scores["feeling"]) ? "T" : "F"; $mbti_score .= ($scores["judging"] > $scores["perceptive"]) ? "J" : "P"; - // IMPORTANTE: El radar debe graficar los puntajes reales del estudiante, - // no valores fijos por tipo MBTI. - - // Header con icono de éxito - $this->content->text .= '
'; - $this->content->text .= '
'; - $this->content->text .= '
'; - $this->content->text .= $this->get_personality_test_icon('4em', 'display: block;', false); - $this->content->text .= ''; - $this->content->text .= '
'; - $this->content->text .= '
' . get_string('test_completed', 'block_personality_test') . '
'; - $this->content->text .= '' . get_string('your_personality_type', 'block_personality_test') . ''; - $this->content->text .= '
'; - - // Test description - $this->content->text .= '
'; - $this->content->text .= ''; - $this->content->text .= ' '; - $this->content->text .= get_string('test_description', 'block_personality_test'); - $this->content->text .= ''; - $this->content->text .= '
'; - - // Tipo MBTI del estudiante - $this->content->text .= '
'; - $this->content->text .= '

' . $mbti_score . '

'; - $mbti_dimensions_key = 'mbti_dimensions_' . strtolower($mbti_score); - $this->content->text .= '' . get_string($mbti_dimensions_key, 'block_personality_test') . ''; - $this->content->text .= '
'; - - // Descripción detallada del tipo MBTI usando strings de idioma - $mbti_key = 'mbti_' . strtolower($mbti_score); - $this->content->text .= '

'; - $this->content->text .= get_string($mbti_key, 'block_personality_test'); - $this->content->text .= '

'; - - // Definimos las etiquetas de las dimensiones para el gráfico usando strings de idioma $mbti_labels = [ get_string('introversion', 'block_personality_test'), get_string('feeling', 'block_personality_test'), @@ -761,7 +350,6 @@ function get_content() get_string('judging', 'block_personality_test') ]; - // El orden de los datos DEBE corresponder exactamente al orden de $mbti_labels. $user_data = [ (float)$scores['introversion'], (float)$scores['feeling'], @@ -773,97 +361,33 @@ function get_content() (float)$scores['judging'], ]; - // Creamos un ID único para el canvas del gráfico usando el ID del usuario $chart_id = 'graficoRadar_' . $USER->id; - - // Insertamos el donde se dibujará el gráfico radar - $this->content->text .= html_writer::start_tag('canvas', [ - 'id' => $chart_id, - 'width' => '400', - 'height' => '400' + + // Call AMD module for Radial Chart + $this->page->requires->js_call_amd('block_personality_test/results_radar', 'init', [ + $chart_id, + $mbti_labels, + $user_data, + get_string('mbti_type', 'block_personality_test') . ': ' . $mbti_score ]); - $this->content->text .= html_writer::end_tag('canvas'); - - // Agregamos el script JavaScript que dibuja el gráfico usando Chart.js - $js_code = " - require(['core/chartjs'], function(Chart) { - var chartId = " . json_encode($chart_id) . "; - var labels = " . json_encode($mbti_labels) . "; - var data = " . json_encode($user_data) . "; - var datasetLabel = " . json_encode(get_string('mbti_type', 'block_personality_test') . ': ' . $mbti_score) . "; - - var el = document.getElementById(chartId); - if(!el) return; - var ctx = el.getContext('2d'); - - new Chart(ctx, { - type: 'radar', - data: { - labels: labels, - datasets: [{ - label: datasetLabel, - data: data, - backgroundColor: 'rgba(0, 191, 145, 0.2)', - borderColor: 'rgba(0, 191, 145, 1)', - pointBackgroundColor: 'rgba(0, 191, 145, 1)', - pointBorderColor: '#fff', - pointHoverBackgroundColor: '#fff', - pointHoverBorderColor: 'rgba(0, 191, 145, 1)' - }] - }, - options: { - scales: { - r: { - beginAtZero: true, - min: 0, - max: 9, - angleLines: { - display: true, - color: 'rgba(0, 0, 0, 0.1)' - }, - grid: { - // AQUÍ QUITAMOS LAS LÍNEAS PARES - color: function(context) { - if (context.tick.value % 2 === 1) { - return 'transparent'; - } - return 'rgba(0, 0, 0, 0.1)'; - }, - lineWidth: 1 - }, - ticks: { - stepSize: 1, - display: true, - backdropColor: 'transparent', - // TAMBIÉN QUITAMOS LOS NÚMEROS PARES DE LAS ETIQUETAS - callback: function(value) { - return value % 2 !== 0 ? value : ''; - }, - font: { - size: 12 - } - }, - pointLabels: { - font: {size: 14} - } - } - } - } - }); - });"; + + $template_data = [ + 'icon' => $this->get_personality_test_icon('4em', 'display: block;', false), + 'mbti_score' => $mbti_score, + 'mbti_dimensions_str' => get_string('mbti_dimensions_' . strtolower($mbti_score), 'block_personality_test'), + 'mbti_description' => get_string('mbti_' . strtolower($mbti_score), 'block_personality_test'), + 'chart_id' => $chart_id, + 'uniqid' => $USER->id, + 'instanceid' => $this->instance->id + ]; - $this->page->requires->js_init_code($js_code); + $this->content->text = $OUTPUT->render_from_template('block_personality_test/student_results', $template_data); - // Cerrar div de resultados - $this->content->text .= '
'; - - // Retornamos el contenido del bloque return $this->content; - } // Fin else (datos de entry existen) - } // Fin else (entry existe) + } + } } - // Devolver el objeto de contenido construido return $this->content; - } // Fin get_content + } } diff --git a/download_csv.php b/download_csv.php index 4fdb1b5..74e8297 100644 --- a/download_csv.php +++ b/download_csv.php @@ -1,8 +1,11 @@ last_action; + // Use updated_at as the last action timestamp + $lastaction = $entry->updated_at; fputcsv($output, [ $student_user->idnumber, diff --git a/download_pdf.php b/download_pdf.php index f4f80d6..0728d8f 100644 --- a/download_pdf.php +++ b/download_pdf.php @@ -1,11 +1,11 @@ + + +

+ Personality Test Icon + {{title}} +

+
+ {{{ description }}} +
+ + {{#delete_confirmation}} +
+

{{#str}}confirm_delete, block_personality_test{{/str}}

+

{{confirm_message}}

+ +
+ {{/delete_confirmation}} + + {{^delete_confirmation}} +
+
+
+
+ +
{{#str}}total_students, block_personality_test{{/str}}
+

{{total_students}}

+
+
+
+ +
+
+
+ +
{{#str}}completed_tests, block_personality_test{{/str}}
+

{{completed_tests}}

+
+
+
+ +
+
+
+ +
{{#str}}in_progress_tests, block_personality_test{{/str}}
+

{{in_progress_tests}}

+
+
+
+ +
+
+
+ +
{{#str}}completion_rate, block_personality_test{{/str}}
+

{{completion_rate}}%

+
+
+
+
+ + {{#has_completed}} +
+
+
+
+
{{#str}}general_statistics, block_personality_test{{/str}}
+
+
+
+ +
+
{{#str}}most_common_types, block_personality_test{{/str}}
+
+ {{#top_types}} +
+
+ +
+ {{rank}} +
+ +
+ {{percentage}}% +
+
+
{{label}}
+ {{count}} +
+
+
+ {{/top_types}} +
+ {{^top_types}} +

{{#str}}no_data_available, block_personality_test{{/str}}

+ {{/top_types}} +
+ + +
+
{{#str}}average_dimensions, block_personality_test{{/str}}
+
+ {{#dimension_stats}} +
+
    +
  • + {{left_label}} + {{left_avg}} +
  • +
  • + {{right_label}} + {{right_avg}} +
  • +
+
+ {{/dimension_stats}} +
+
+
+
+
+
+
+ {{/has_completed}} + +
+ {{#show_table}} +
+
+
{{#str}}participants_list, block_personality_test{{/str}}
+
+
+ + +
+ + + + + + + + + + + + + {{#list}} + + + + + + + + + {{/list}} + {{^list}} + + + + {{/list}} + +
{{#str}}student_name, block_personality_test{{/str}}{{#str}}email, block_personality_test{{/str}}{{#str}}status, block_personality_test{{/str}}{{#str}}mbti_type, block_personality_test{{/str}}{{#str}}test_date, block_personality_test{{/str}}{{#str}}actions, block_personality_test{{/str}}
+
+ {{{userpicture}}} + {{fullname}} +
+
{{email}} + {{#is_completed}} + {{#str}}completed_status, block_personality_test{{/str}} + {{/is_completed}} + {{^is_completed}} + {{#str}}in_progress_status, block_personality_test{{/str}} +
{{answered}}/72 {{#str}}questions, block_personality_test{{/str}} + {{/is_completed}} +
+ {{#mbti_type}} + {{.}} + {{/mbti_type}} + {{^mbti_type}}-{{/mbti_type}} + {{created_at}} + + {{#str}}view, block_personality_test{{/str}} + + + {{#str}}delete, block_personality_test{{/str}} + +
+
+ {{#str}}no_results_search, block_personality_test, {{search_term}}{{/str}} +
+
+
+ + +
+ {{{pagination}}} +
+
+
+ {{/show_table}} + {{^show_table}} +
+ +
{{#str}}no_participants, block_personality_test{{/str}}
+

{{#str}}no_participants_message, block_personality_test{{/str}}

+
+ {{/show_table}} +
+ {{/delete_confirmation}} + +
+ + {{#str}}back_to_course, block_personality_test{{/str}} + +
+ + +{{#js}} +require(['jquery'], function($) { + var timeout = null; + var container = $('#personality-test-results-region'); + + // Dynamic Search (AJAX) Delegated + container.on('input', '#searchInput', function() { + var input = $(this); + if (timeout) clearTimeout(timeout); + var searchTerm = input.val(); + + timeout = setTimeout(function() { + loadResults(searchTerm, 0); + }, 300); + }); + + container.on('click', '.pagination a', function(e) { + e.preventDefault(); + var href = $(this).attr('href'); + if (!href) return; + + var urlParams = new URLSearchParams(href.split('?')[1]); + var page = urlParams.get('page') || 0; + var searchTerm = container.find('#searchInput').val() || ''; + + loadResults(searchTerm, page); + }); + + function loadResults(search, page) { + var url = '{{admin_url}}'; + var data = { + cid: {{courseid}}, + search: search, + page: page, + action: 'list' + }; + + container.css('opacity', '0.6'); + + $.get(url, data, function(response) { + var responseObj = $('
').html(response); + var newContent = responseObj.find('#personality-test-results-region').html(); + + if (newContent) { + container.html(newContent); + var input = container.find('#searchInput'); + if (input.length) { + input.focus(); + var tmpStr = input.val(); + input.val(''); + input.val(tmpStr); + } + } + container.css('opacity', '1'); + }); + } +}); +{{/js}} diff --git a/templates/individual_view.mustache b/templates/individual_view.mustache new file mode 100644 index 0000000..c20d97a --- /dev/null +++ b/templates/individual_view.mustache @@ -0,0 +1,163 @@ +{{#in_progress}} +
+ + + +
+{{/in_progress}} + +{{#is_completed}} +
+ + +
+
+
+
+

+ Personality Test Icon{{individual_results_title}} +

+
+
+
+
+

{{user_fullname}}

+

{{email_label}}: {{user_email}}

+

{{date_label}}: {{test_date}}

+

{{mbti_label}}: {{mbti_type}}

+
+
+
+
+
+
+ +
+ + +
+
+
+
{{dimensions_title}}
+
+
+ {{#dimension_bars}} +
+
+ {{label1}} ({{value1}}) + {{label2}} ({{value2}}) +
+
+
+ {{percent1_display}}% +
+
+ {{percent2_display}}% +
+
+
+ {{/dimension_bars}} +
+
+
+ + +
+
+
+
{{summary_actions_title}}
+
+
+ +
+

{{mbti_type}}

+

({{mbti_dimensions_str}})

+

{{mbti_description}}

+
+ + + +
+
+
+ +
+ + +
+
+
+
+
{{detailed_scores_title}}
+
+
+
+ + + + + + + + + + {{#score_rows}} + + + + + + {{/score_rows}} + +
{{dimension_header}}{{score_header}}{{preference_header}}
{{label1}} - {{label2}}{{value1}} - {{value2}}{{dominant}}
+
+
+
+
+
+ + + + +
+{{/is_completed}} diff --git a/templates/student_continue.mustache b/templates/student_continue.mustache new file mode 100644 index 0000000..3fefe20 --- /dev/null +++ b/templates/student_continue.mustache @@ -0,0 +1,50 @@ +
+
+ {{{icon}}} +
{{#str}}test_title, block_personality_test{{/str}}
+ {{#str}}discover_your_personality, block_personality_test{{/str}} +
+ +
+ + + {{#str}}test_description, block_personality_test{{/str}} + +
+ + {{#all_answered}} +
+
+ +
+ {{#str}}all_answered_title, block_personality_test{{/str}}
+ {{#str}}all_answered_message, block_personality_test{{/str}} +
+
+
+ {{/all_answered}} + +
+
+ {{#str}}your_progress, block_personality_test{{/str}} + {{answered_count}}/72 +
+
+
+
+ {{progress_percentage_formatted}}% {{#str}}completed, block_personality_test{{/str}} +
+ +
+ {{#all_answered}} + + {{#str}}finish_test_now, block_personality_test{{/str}} + + {{/all_answered}} + {{^all_answered}} + + {{#str}}continue_test, block_personality_test{{/str}} + + {{/all_answered}} +
+
diff --git a/templates/student_invitation.mustache b/templates/student_invitation.mustache new file mode 100644 index 0000000..10befd9 --- /dev/null +++ b/templates/student_invitation.mustache @@ -0,0 +1,30 @@ +
+
+ {{{icon}}} +
{{#str}}test_title, block_personality_test{{/str}}
+ {{#str}}discover_your_personality, block_personality_test{{/str}} +
+ +
+
+
+
+ + {{#str}}what_is_mbti, block_personality_test{{/str}} +
+

{{#str}}test_description, block_personality_test{{/str}}

+
    +
  • {{#str}}feature_72_questions, block_personality_test{{/str}}
  • +
  • {{#str}}feature_16_types, block_personality_test{{/str}}
  • +
  • {{#str}}feature_instant_results, block_personality_test{{/str}}
  • +
+
+
+
+ + +
diff --git a/templates/student_results.mustache b/templates/student_results.mustache new file mode 100644 index 0000000..7e4d740 --- /dev/null +++ b/templates/student_results.mustache @@ -0,0 +1,49 @@ +
+
+
+ {{{icon}}} + +
+
{{#str}}test_completed, block_personality_test{{/str}}
+ {{#str}}your_personality_type, block_personality_test{{/str}} +
+ +
+ + + {{#str}}test_description, block_personality_test{{/str}} + +
+ +
+

{{mbti_score}}

+ {{mbti_dimensions_str}} +
+ +

+ {{{mbti_description}}} +

+ + +
+{{#js}} +require(['jquery'], function($) { + var instanceId = "{{instanceid}}"; + /* Check if instanceId is valid before proceeding */ + if (instanceId && window.location.hash) { + var targetHash = "#inst" + instanceId; + if (window.location.hash === targetHash) { + /* Add a small delay to ensure rendering is complete */ + setTimeout(function() { + var $target = $(targetHash); + if ($target.length) { + /* Scroll to element with some top offset (e.g. 100px for header) */ + $('html, body').animate({ + scrollTop: $target.offset().top - 100 + }, 500); + } + }, 300); + } + } +}); +{{/js}} diff --git a/templates/teacher_dashboard.mustache b/templates/teacher_dashboard.mustache new file mode 100644 index 0000000..51da78b --- /dev/null +++ b/templates/teacher_dashboard.mustache @@ -0,0 +1,58 @@ +
+ {{{icon}}} +
{{#str}}management_title, block_personality_test{{/str}}
+ {{#str}}course_overview, block_personality_test{{/str}} +
+ +{{^has_data}} +
+
{{#str}}participation_stats, block_personality_test{{/str}}
+
    +
  • {{#str}}total_participants, block_personality_test{{/str}}: {{total_students}}
  • +
  • {{#str}}completed_tests, block_personality_test{{/str}}: 0
  • +
  • {{#str}}in_progress_tests, block_personality_test{{/str}}: {{in_progress}}
  • +
+
+

{{#str}}sin_datos_estudiantes, block_personality_test{{/str}}

+

{{#str}}waiting_first_completion, block_personality_test{{/str}}

+
+{{/has_data}} + +{{#has_data}} +
+ {{#str}}participation_stats, block_personality_test{{/str}}: + {{completed_str}} +
+ +
{{#str}}titulo_resultados_estudiantes, block_personality_test{{/str}}
+ + +
{{#str}}titulo_distribucion_rasgos, block_personality_test{{/str}}
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + +{{/has_data}} +{{#admin_url}} + +{{/admin_url}} diff --git a/templates/test_view.mustache b/templates/test_view.mustache new file mode 100644 index 0000000..3774a69 --- /dev/null +++ b/templates/test_view.mustache @@ -0,0 +1,276 @@ +
+
+ Personality Test Icon +
+ +

{{test_page_title}}

+
+ {{{test_intro_p1}}} + {{{test_intro_p2}}} +
+
+
+ {{test_benefit_note}} {{test_benefit_required}} (*) +
+ +
+
+
    + {{#questions}} +
  • +
    {{question_text}}
    +
    + + +
    + +
  • + {{/questions}} +
+ + + {{#hidden_answers}} + + {{/hidden_answers}} + +
+ + + + +
+ + + + +
+ +
+
+ + diff --git a/version.php b/version.php index 437b26a..6855bb5 100644 --- a/version.php +++ b/version.php @@ -1,17 +1,17 @@ version = 2025122200; -$plugin->requires = 2022112800; +$plugin->version = 2026010800; +$plugin->requires = 2022041900; // Moodle 4.0+ $plugin->component = 'block_personality_test'; $plugin->maturity = MATURITY_STABLE; -$plugin->release = '2.0.1'; +$plugin->release = '2.0.2'; diff --git a/view.php b/view.php index fb9961a..73efa5b 100644 --- a/view.php +++ b/view.php @@ -1,4 +1,13 @@ record_exists('block_instances', array('blockname' => 'personality_test', 'parentcontextid' => $context->id))) { + redirect(new moodle_url('/course/view.php', array('id' => $courseid))); +} + // If a user with reporting capability tries to open the student test view, redirect them to admin silently if (has_capability('block/personality_test:viewreports', $context) && !has_capability('block/personality_test:taketest', $context)) { redirect(new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)), get_string('teachers_redirect_message', 'block_personality_test'), null, \core\output\notification::NOTIFY_INFO); @@ -117,306 +131,71 @@ echo $OUTPUT->header(); echo $OUTPUT->box_start('generalbox'); -// Display personality test icon centered above title -$iconurl = new moodle_url('/blocks/personality_test/pix/personality_test_icon.svg'); -echo '
'; -echo 'Personality Test Icon'; -echo '
'; - -echo "

".get_string('test_page_title', 'block_personality_test')."

"; -echo " -
-".get_string('test_intro_p1', 'block_personality_test')." -".get_string('test_intro_p2', 'block_personality_test')." -
-
-
- ".get_string('test_benefit_note', 'block_personality_test')." ".get_string('test_benefit_required', 'block_personality_test')." (*) -
-"; - -$action_form = new moodle_url('/blocks/personality_test/save.php'); -?> - -
-
-
    - $field)) ? $existing_response->$field : null; - ?> - -
  • -
    -
    - - -
    - -
  • - -
- - - = $start_question && $i <= $end_question) { - continue; - } - - $field = "q{$i}"; - if (isset($existing_response->$field) && $existing_response->$field !== null) { - echo ''; - } - } - } - ?> - -
- - - - -
- - - - -
- -
- - +$should_auto_scroll = ($existing_response && $answered_count > 0 && $answered_count < 72 && !$scroll_to_finish); +$action_form = new moodle_url('/blocks/personality_test/save.php'); - (new moodle_url('/blocks/personality_test/pix/icon.svg'))->out(), + 'test_page_title' => get_string('test_page_title', 'block_personality_test'), + 'test_intro_p1' => get_string('test_intro_p1', 'block_personality_test'), + 'test_intro_p2' => get_string('test_intro_p2', 'block_personality_test'), + 'test_benefit_note' => get_string('test_benefit_note', 'block_personality_test'), + 'test_benefit_required' => get_string('test_benefit_required', 'block_personality_test'), + 'action_form' => $action_form->out(), + 'questions' => $questions, + 'hidden_answers' => $hidden_answers, + 'courseid' => $courseid, + 'page' => $page, + 'sesskey' => sesskey(), + 'show_previous' => ($page > 1), + 'show_next' => ($page < $total_pages), + 'show_finish' => ($page >= $total_pages), + 'btn_previous_label' => get_string('btn_previous', 'block_personality_test'), + 'btn_next_label' => get_string('btn_next', 'block_personality_test'), + 'btn_finish_label' => get_string('btn_finish', 'block_personality_test'), + 'wwwroot' => $CFG->wwwroot, + 'should_auto_scroll' => $should_auto_scroll, + 'scroll_to_finish' => $scroll_to_finish, +]; + +echo $OUTPUT->render_from_template('block_personality_test/test_view', $template_data); echo $OUTPUT->box_end(); echo $OUTPUT->footer(); diff --git a/view_individual.php b/view_individual.php index 818bca4..1dc12ed 100644 --- a/view_individual.php +++ b/view_individual.php @@ -1,4 +1,13 @@ get_record('course', array('id' => $courseid), '*', MUST_EXIST); $context = context_course::instance($courseid); +// Check if the block is added to the course +if (!$DB->record_exists('block_instances', array('blockname' => 'personality_test', 'parentcontextid' => $context->id))) { + redirect(new moodle_url('/course/view.php', array('id' => $courseid))); +} + // Silent redirect if user lacks report capability if (!has_capability('block/personality_test:viewreports', $context)) { redirect(new moodle_url('/course/view.php', array('id' => $courseid))); @@ -58,15 +72,10 @@ echo $OUTPUT->header(); +$template_data = []; + // Verificar si el test está completado if ($test_result->is_completed == 0) { - // Mostrar alerta de progreso - echo "
"; - echo ""; - - // Botón para volver - echo ""; - echo "
"; - - echo $OUTPUT->footer(); - exit; -} - -// Si llegamos aquí, el test está completado, mostrar resultados completos -// Calcular tipo MBTI -$mbti = ''; -$mbti .= ($test_result->extraversion > $test_result->introversion) ? 'E' : 'I'; -$mbti .= ($test_result->sensing > $test_result->intuition) ? 'S' : 'N'; -$mbti .= ($test_result->thinking >= $test_result->feeling) ? 'T' : 'F'; -$mbti .= ($test_result->judging > $test_result->perceptive) ? 'J' : 'P'; - -echo "
"; - -// Header con información del estudiante -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "

"; -$iconurl = new moodle_url('/blocks/personality_test/pix/personality_test_icon.svg'); -echo "Personality Test Icon" . get_string('individual_results', 'block_personality_test') . ""; -echo "

"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "

" . fullname($user) . "

"; -echo "

" . get_string('email', 'block_personality_test') . ": " . $user->email . "

"; -echo "

" . get_string('test_date', 'block_personality_test') . ": " . date('d/m/Y H:i', $test_result->created_at) . "

"; -echo "

" . get_string('mbti_type', 'block_personality_test') . ": " . $mbti . "

"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; - -// Resultados detallados -echo "
"; - -// Dimensiones principales -echo "
"; -echo "
"; -echo "
"; -echo "
" . get_string('personality_dimensions', 'block_personality_test') . "
"; -echo "
"; -echo "
"; - -// Función para mostrar barras de progreso comparativas -function render_dimension_bar($label1, $value1, $label2, $value2, $max_value = 100) { - $total = $value1 + $value2; - $percent1 = $total > 0 ? ($value1 / $total) * 100 : 50; - $percent2 = $total > 0 ? ($value2 / $total) * 100 : 50; - - echo "
"; - echo "
"; - echo "" . $label1 . " (" . $value1 . ")"; - echo "" . $label2 . " (" . $value2 . ")"; - echo "
"; - echo "
"; - echo "
"; - echo round($percent1, 1) . "%"; - echo "
"; - echo "
"; - echo round($percent2, 1) . "%"; - echo "
"; - echo "
"; - echo "
"; -} - -render_dimension_bar( - get_string('extraversion', 'block_personality_test'), - $test_result->extraversion, - get_string('introversion', 'block_personality_test'), - $test_result->introversion -); - -render_dimension_bar( - get_string('sensing', 'block_personality_test'), - $test_result->sensing, - get_string('intuition', 'block_personality_test'), - $test_result->intuition -); - -render_dimension_bar( - get_string('thinking', 'block_personality_test'), - $test_result->thinking, - get_string('feeling', 'block_personality_test'), - $test_result->feeling -); - -render_dimension_bar( - get_string('judging', 'block_personality_test'), - $test_result->judging, - get_string('perceptive', 'block_personality_test'), - $test_result->perceptive -); - -echo "
"; -echo "
"; -echo "
"; - -// Resumen y acciones -echo "
"; -echo "
"; -echo "
"; -echo "
" . get_string('summary_actions', 'block_personality_test') . "
"; -echo "
"; -echo "
"; - -// Usar cadenas de idioma para las descripciones MBTI -$mbti_key = 'mbti_' . strtolower($mbti); -$mbti_dimensions_key = 'mbti_dimensions_' . strtolower($mbti); - -echo "
"; -echo "

" . $mbti . "

"; -echo "

(" . get_string($mbti_dimensions_key, 'block_personality_test') . ")

"; -echo "

" . get_string($mbti_key, 'block_personality_test') . "

"; -echo "
"; - -echo ""; - -echo "
"; -echo "
"; -echo "
"; - -echo "
"; - -// Datos detallados en tabla -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "
" . get_string('detailed_scores', 'block_personality_test') . "
"; -echo "
"; -echo "
"; -echo "
"; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; - -$dimensions = [ - [get_string('extraversion', 'block_personality_test'), get_string('introversion', 'block_personality_test'), $test_result->extraversion, $test_result->introversion], - [get_string('sensing', 'block_personality_test'), get_string('intuition', 'block_personality_test'), $test_result->sensing, $test_result->intuition], - [get_string('thinking', 'block_personality_test'), get_string('feeling', 'block_personality_test'), $test_result->thinking, $test_result->feeling], - [get_string('judging', 'block_personality_test'), get_string('perceptive', 'block_personality_test'), $test_result->judging, $test_result->perceptive] -]; + // Preparar score rows + $score_rows = []; + foreach ($raw_dimensions as $dim) { + $dominant = ($dim[1] >= $dim[3]) ? $dim[0] : $dim[2]; + $score_rows[] = [ + 'label1' => $dim[0], + 'value1' => $dim[1], + 'label2' => $dim[2], + 'value2' => $dim[3], + 'dominant' => $dominant + ]; + } -foreach ($dimensions as $dim) { - $label1 = $dim[0]; - $label2 = $dim[1]; - $value1 = $dim[2]; - $value2 = $dim[3]; - $dominant = ($value1 >= $value2) ? $label1 : $label2; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; + $template_data = [ + 'in_progress' => false, + 'is_completed' => true, + 'iconurl' => (new moodle_url('/blocks/personality_test/pix/icon.svg'))->out(), + 'individual_results_title' => get_string('individual_results', 'block_personality_test'), + 'user_fullname' => fullname($user), + 'email_label' => get_string('email', 'block_personality_test'), + 'user_email' => $user->email, + 'date_label' => get_string('test_date', 'block_personality_test'), + 'test_date' => date('d/m/Y H:i', $test_result->created_at), + 'mbti_label' => get_string('mbti_type', 'block_personality_test'), + 'mbti_type' => $mbti, + 'dimensions_title' => get_string('personality_dimensions', 'block_personality_test'), + 'dimension_bars' => $dimension_bars, + 'summary_actions_title' => get_string('summary_actions', 'block_personality_test'), + 'mbti_dimensions_str' => get_string($mbti_dimensions_key, 'block_personality_test'), + 'mbti_description' => get_string($mbti_key, 'block_personality_test'), + 'download_url' => (new moodle_url('/blocks/personality_test/download_pdf.php', array('userid' => $userid, 'cid' => $courseid)))->out(false), + 'download_pdf_label' => get_string('download_pdf', 'block_personality_test'), + 'delete_url' => (new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid, 'action' => 'delete', 'userid' => $userid, 'sesskey' => sesskey())))->out(false), + 'confirm_delete_msg' => get_string('confirm_delete_individual', 'block_personality_test'), + 'delete_results_label' => get_string('delete_results', 'block_personality_test'), + 'detailed_scores_title' => get_string('detailed_scores', 'block_personality_test'), + 'dimension_header' => get_string('dimension', 'block_personality_test'), + 'score_header' => get_string('score', 'block_personality_test'), + 'preference_header' => get_string('preference', 'block_personality_test'), + 'score_rows' => $score_rows, + 'back_to_admin_url' => (new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)))->out(false), + 'back_to_admin_label' => get_string('back_to_admin', 'block_personality_test'), + 'back_to_course_url' => (new moodle_url('/course/view.php', array('id' => $courseid)))->out(false), + 'back_to_course_label' => get_string('back_to_course', 'block_personality_test') + ]; } -echo ""; -echo "
" . get_string('dimension', 'block_personality_test') . "" . get_string('score', 'block_personality_test') . "" . get_string('preference', 'block_personality_test') . "
" . $label1 . " - " . $label2 . "" . $value1 . " - " . $value2 . "" . $dominant . "
"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; -echo "
"; - -echo "
"; - -// Botones de navegación con diseño moderno -echo html_writer::start_div('mt-5 text-center d-flex gap-3 justify-content-center'); -echo html_writer::link( - new moodle_url('/blocks/personality_test/admin_view.php', array('cid' => $courseid)), - '' . get_string('back_to_admin', 'block_personality_test'), - array('class' => 'btn btn-secondary btn-modern mr-3') -); -echo html_writer::link( - new moodle_url('/course/view.php', array('id' => $courseid)), - '' . get_string('back_to_course', 'block_personality_test'), - array('class' => 'btn btn-modern', 'style' => 'background: linear-gradient(135deg, #00bf91 0%, #00a07a 100%); border: none; color: white;') -); -echo html_writer::end_div(); +echo $OUTPUT->render_from_template('block_personality_test/individual_view', $template_data); echo $OUTPUT->footer(); ?>