diff --git a/README.md b/README.md index a085538a..97e9f979 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [GitHub Star Shelf](plugins/start3208/github-star-shelf/) | Turn your GitHub stars into collections you can search and ask the AI to explain in plain language: from the README alone, or after it has read a shallow clone of the code. One session per project, your own notes, and collections the Agent can arrange | [start3208](https://github.com/start3208) | | [Plugin Listing Workbench](plugins/zhuyankarl/submission-workbench/) | Prepare a plugin submission: fill in the manifest and listing fields, check every required field and cross-file consistency, then download a reviewable listing package that names what is missing; a bundled Skill gives the Agent the same checklist | [zhuyankarl](https://github.com/zhuyankarl) | | [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) | +| [Teacher Evaluation Dashboard](plugins/salvadorfernandezm/teacher-evaluation-dashboard/) | Turn a teaching-evaluation workbook into an interactive dashboard: the average and the difference against the historical average by teacher, term, programme and item, the participation rate, the students' written comments, and the anomalies the file itself contains | [salvadorfernandezm](https://github.com/salvadorfernandezm) |
Preview: Weekly Planner @@ -150,6 +151,15 @@ The preview uses synthetic data. The app interface is currently in Chinese. See
+
+Preview: Teacher Evaluation Dashboard + +![Teacher Evaluation Dashboard showing the filters, the headline figures and the ranking by teacher with synthetic data](plugins/salvadorfernandezm/teacher-evaluation-dashboard/docs/preview.png) + +The preview uses synthetic data. The app interface is currently in Spanish. See its [README](plugins/salvadorfernandezm/teacher-evaluation-dashboard/README.md) for the workbook layout, the computation rules, and compatibility notes. + +
+ ## Getting started ### Requirements diff --git a/README.zh-CN.md b/README.zh-CN.md index 79d64bff..33111976 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -102,6 +102,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [GitHub 收藏夹](plugins/start3208/github-star-shelf/README.zh-CN.md) | 把 GitHub Star 分进收藏夹,按名称、README 和备注搜索;让 AI 用大白话讲清每个项目:只看 README 讲,或读一遍浅克隆的代码再讲。一个项目一个会话,可以写备注,也能让 Agent 整理收藏夹 | [start3208](https://github.com/start3208) | | [插件上架材料工作台](plugins/zhuyankarl/submission-workbench/README.zh-CN.md) | 填写插件清单与上架信息,逐项核对必填字段与内容一致性,生成可审核的上架材料包并标出缺失项;内置 Skill 让 Agent 拿到同一套检查清单 | [zhuyankarl](https://github.com/zhuyankarl) | | [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) | +| [教师评价分析看板](plugins/salvadorfernandezm/teacher-evaluation-dashboard/) | 把教师教学工作簿变成可交互的分析看板:按教师、学期、专业和题目查看当前均分与历史均分的差异、参与率、学生文字评论,以及文件自身暴露出的异常 | [salvadorfernandezm](https://github.com/salvadorfernandezm) |
预览:周计划 @@ -150,6 +151,15 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求
+
+预览:教师评价分析看板 + +![教师评价分析看板,使用合成数据展示筛选器、核心指标与按教师排名](plugins/salvadorfernandezm/teacher-evaluation-dashboard/docs/preview.png) + +预览使用合成数据,应用界面目前为西班牙语。工作簿结构、计算口径与兼容性说明见作品 [README](plugins/salvadorfernandezm/teacher-evaluation-dashboard/README.md)。 + +
+ ## 开始使用 ### 使用要求 diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/.minimax-plugin/plugin.json b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/.minimax-plugin/plugin.json new file mode 100644 index 00000000..63fd200f --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/.minimax-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "name": "teacher-evaluation-dashboard", + "displayName": "Teacher Evaluation Dashboard", + "version": "1.4.0", + "description": "Turns a teaching-evaluation workbook into an interactive dashboard: the average of the round per teacher, term, programme and item, the historical average for comparison, the participation rate, and the students' written comments.", + "author": "salvadorfernandezm", + "icon": "icon.png", + "category": "Education", + "exampleQueries": [ + "Open the teacher evaluation dashboard.", + "Show the evaluation analysis by item and by term." + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/LICENSE b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/LICENSE new file mode 100644 index 00000000..f19a36c7 --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Salvador Fernandez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/README.md b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/README.md new file mode 100644 index 00000000..83bc414a --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/README.md @@ -0,0 +1,131 @@ +# Teacher Evaluation Dashboard + +Turns a teaching-evaluation workbook into an interactive analysis dashboard: the current-period +average for every teacher, term, programme and item, the historical average for comparison, the +participation rate, and the students' written comments. + +The app ships with a **synthetic demo workbook**. Import your own `.xlsx` with the same layout to +analyse a real evaluation round; nothing leaves your machine. + +![The dashboard with the synthetic demo workbook: the filters, the headline figures and the ranking by teacher](docs/preview.png) + +The preview uses synthetic data. The app interface is in Spanish. + +## What it shows + +- **Headline figures** — average for the current period, the difference against the historical + average, the participation rate, and how many written comments the selection contains. +- **By teacher** — a ranking where each bar carries the current average, a mark for the historical + average and the participation of that teacher's own students. Clicking a bar filters the whole + page by that teacher. +- **By term** and **by programme** — the same comparison across course terms and specialisms. +- **By item** — the profile of the 17-item instrument, current average against historical. +- **Heatmap** — every course against every item; selecting a cell opens the course detail with + the 17 items, the difference against the historical value and the course's comments. +- **Comments** — the students' free-text answers, verbatim. +- **Data notes** — the anomalies the dashboard found in the file itself (courses without a + historical baseline, courses whose response count differs from the number of students + summoned, co-taught courses, courses split between several teachers, and columns the + dashboard ignores). + +All filters — term, programme, teacher, item and a free-text search over teachers, courses and +comments — apply at once and recompute every section. + +**Naming the round.** The page shows the period carried by the workbook. When the workbook names +one — `Promedio 2026A`, `Promedio 2027A` — the *Período* field displays it and stays read-only, so +a period remembered in the browser can never mislabel the round. When the workbook names no period +(`Promedio actual`), the field is yours: it renames the round for the whole page — the headline +figure, the legends, the chart titles and the course detail — without touching the file. The value +is remembered in the browser, and an empty field keeps the wording of the workbook. + +## Install and open + +1. Download or clone this directory. +2. In MiniMax Code, open the Plugins panel and install the package, or copy + `plugins//teacher-evaluation-dashboard/` into your MiniMax Code plugin folder. +3. Ask the Agent to "Open the teacher evaluation dashboard", or pick it in the File Panel. + +The page opens at `/dashboard`. + +**Importing your own round.** *Importar Excel* replaces the bundled workbook; *Restaurar datos +originales* brings the bundled one back. *Descargar plantilla* downloads the workbook currently +in use, so it can be opened in a spreadsheet, edited (renaming the period column, adding a +participation column, removing a column) and imported back. + +## Workbook layout + +The Node service reads the workbook at startup with a small built-in XLSX reader, so the package +has no runtime dependencies. The instrument is fixed by contract and never inferred from the +file; the shape of the file around it is not: + +- Sheet `Estadística` with one row per course and item, with the items numbered `1` to `17`. + `Reactivo` holds the number followed by the item text. +- The columns `ID programa`, `ID especialidad`, `ID profesor`, `Semestre`, `Reactivo`, + `Histórico`, `Comentarios`, `Participaron` and `Convocados` are required; common alternative + spellings are accepted. +- The column with the average of the period is found by shape: any header of the form + `Promedio ` (`Promedio 2026A`, `Promedio 2027A`, …). The period is read from that + header and shown throughout the page, so the same package analyses any round without being + edited. A header that names no period — `Promedio actual` — is accepted too, so a template can + be reused every semester without renaming anything; the page then speaks of "Promedio actual" + until a period is typed in the *Período* field. + A file with two period columns is rejected with a message naming both, and a header that looks + like a misspelling is pointed out with the right spelling. +- An optional column whose name refers to the participation percentage (for example + `Participación %`) declares the participation of each teacher and is used in place of the + calculated one. +- Extra columns are ignored and listed as a data note, so an edited template imports without + being reshaped. +- Sheet `Padrón` (optional) with `ID`, `Nombre`, `Materia`, `Programa`, `Especialidad`, `Semestre`. + When `ID especialidad` is empty in the evaluation sheet, the programme from `Padrón` is used. + +A workbook that does not honour the contract is rejected with an explicit message that names +what is missing, so a wrong file never silently produces a wrong dashboard. + +## How the numbers are computed + +- **Average** — the mean of the per-item averages, one per course and item, not weighted by the + number of responses. +- **Difference against historical** — computed only over the records that have a historical + baseline, so both sides of the comparison describe the same records. +- **Participation** — counted per group of (course, teacher), so a course that is taught by + several teachers keeps the students of each one; the groups are then summed over the + selection. When the file declares a participation percentage per teacher, that value is used + instead of the calculated one and the difference is reported. + +## Tested environment + +- Minimum client: MiniMax Code 3.1.2 — the package declares `surface.window` and nothing that + arrived later. It declares no `permissions` and no `engines` bound. +- Tested on MiniMax Code 3.1.22 on Windows 11 (x64). +- Client acceptance in that session: initial render and structure, cross-filtering by term, + programme, teacher, item and free text, the course detail dialog, heatmap navigation, the + empty state, the light and dark themes, importing a workbook and restoring the bundled one, + the template download, the period field (read-only when the workbook names a period, editable + when it does not), plus console and network checks. The Node service was exercised directly + against the bundled workbook and its output was compared record by record with an independent + read of the same file. A workbook renamed to a different period, with an extra column and a + declared participation percentage, was imported and rendered as well. Workbooks headed + `Promedio actual`, `Promedio 2027A` and `Promedio 2026B` were imported in turn to check that + the period of the workbook always wins over a period remembered in the browser. + +## Data & access + +- **Files read** — `miniapp/node/data/estadistica.xlsx`, the bundled synthetic demo workbook + (read-only). A workbook you import is read once and then stored by the app, not read from + anywhere else. +- **Files written** — `context.dataDir` only: an imported workbook is stored there as + `imported-source.xlsx`, written atomically, and **Restore original data** deletes it. Filter, + theme and period choices are kept in the page's local storage. +- **Network hosts** — none. The Node service listens only on the Host-assigned loopback port and + serves the page and its own routes, including `/api/template`, which returns the workbook in + use as a download for editing. +- **Processes** — none. No external program, shell command or package is started. +- **Agent turns** — none. **Conversations read** — none. **Tools or Connectors called** — none. +- **Microphone, camera, notifications** — not used. **Host navigation** — not read. +- **File extensions handled** — `.xlsx`, through the page's own file input. This is not a Host + file handler: opening an `.xlsx` in MiniMax Code does not launch this app. + +## License + +MIT — see `LICENSE`. diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/docs/preview.png b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/docs/preview.png new file mode 100644 index 00000000..5055c118 Binary files /dev/null and b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/docs/preview.png differ diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/icon.png b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/icon.png differ diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/app.js b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/app.js new file mode 100644 index 00000000..1e17027b --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/app.js @@ -0,0 +1,1606 @@ +/** + * Sistema de análisis de la Evaluación Docente — cliente del Mini App. + * + * El servicio Node expone el conjunto de evaluaciones ya normalizado; este + * módulo aplica los filtros cruzados y calcula cada corte en el navegador para + * que la interacción sea inmediata. + */ + +const SCALE_MIN = 0; +const SCALE_MAX = 10; +const VIEW_STATE_KEY = 'evaluacion-docente:view-state:v1'; + +const state = { + dataset: null, + filters: { term: 'all', specialty: 'all', teacher: 'all', item: 'all', text: '' }, + theme: 'auto', + period: '', + currentLabel: 'Promedio', + periodTyped: '', +}; + +const elements = { + sourceSummary: document.getElementById('source-summary'), + periodInput: document.getElementById('period-input'), + periodHint: document.getElementById('period-hint'), + errorBanner: document.getElementById('error-banner'), + errorMessage: document.getElementById('error-message'), + retryButton: document.getElementById('retry-button'), + loading: document.getElementById('loading'), + dashboard: document.getElementById('dashboard'), + dashboardContent: document.getElementById('dashboard-content'), + emptyState: document.getElementById('empty-state'), + filterTerm: document.getElementById('filter-term'), + filterSpecialty: document.getElementById('filter-specialty'), + filterTeacher: document.getElementById('filter-teacher'), + filterItem: document.getElementById('filter-item'), + filterText: document.getElementById('filter-text'), + clearFilters: document.getElementById('clear-filters'), + activeFilters: document.getElementById('active-filters'), + kpiCurrent: document.getElementById('kpi-current'), + kpiCurrentLabel: document.getElementById('kpi-current-label'), + kpiCurrentDetail: document.getElementById('kpi-current-detail'), + kpiDelta: document.getElementById('kpi-delta'), + kpiDeltaDetail: document.getElementById('kpi-delta-detail'), + kpiParticipation: document.getElementById('kpi-participation'), + kpiParticipationDetail: document.getElementById('kpi-participation-detail'), + kpiComments: document.getElementById('kpi-comments'), + kpiCommentsDetail: document.getElementById('kpi-comments-detail'), + chartTeachers: document.getElementById('chart-teachers'), + chartTerms: document.getElementById('chart-terms'), + chartSpecialties: document.getElementById('chart-specialties'), + chartItems: document.getElementById('chart-items'), + heatmap: document.getElementById('heatmap'), + heatmapCaption: document.getElementById('heatmap-caption'), + hintTeachers: document.getElementById('hint-teachers'), + hintItems: document.getElementById('hint-items'), + matrixScaleMin: document.getElementById('matrix-scale-min'), + matrixScaleMax: document.getElementById('matrix-scale-max'), + commentsList: document.getElementById('comments-list'), + dataNotes: document.getElementById('data-notes'), + methodNotes: document.getElementById('method-notes'), + fileInput: document.getElementById('file-input'), + downloadTemplate: document.getElementById('download-template'), + resetData: document.getElementById('reset-data'), + themeToggle: document.getElementById('theme-toggle'), + dialog: document.getElementById('course-dialog'), + dialogTitle: document.getElementById('dialog-title'), + dialogSubtitle: document.getElementById('dialog-subtitle'), + dialogBody: document.getElementById('dialog-body'), + dialogClose: document.getElementById('dialog-close'), + toast: document.getElementById('toast'), +}; + +/* ---------------------------------------------------------------- utilities */ + +const numberFormat = new Intl.NumberFormat('es-MX', { maximumFractionDigits: 2 }); + +/** + * @param {number | null} value + * @param {number} [digits] + * @returns {string} + */ +function formatScore(value, digits = 2) { + if (value === null || value === undefined || !Number.isFinite(value)) return '—'; + return value.toFixed(digits); +} + +/** + * @param {number | null} value + * @returns {string} + */ +function formatDelta(value) { + if (value === null || value === undefined || !Number.isFinite(value)) return '—'; + const sign = value > 0 ? '+' : ''; + return `${sign}${value.toFixed(2)}`; +} + +/** + * @param {number[]} values + * @returns {number | null} + */ +function mean(values) { + if (!values.length) return null; + return values.reduce((total, value) => total + value, 0) / values.length; +} + +/** + * @param {string} text + * @returns {string} + */ +function normalizeText(text) { + return String(text ?? '') + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .trim(); +} + +/** + * @param {number} value + * @param {number} min + * @param {number} max + * @returns {number} + */ +function clamp(value, min, max) { + return Math.min(Math.max(value, min), max); +} + +/** + * @param {string} name + * @param {Record | null} attributes + * @param {Element[]} [children] + * @returns {SVGElement} + */ +function svgElement(name, attributes = null, children = []) { + const node = document.createElementNS('http://www.w3.org/2000/svg', name); + if (attributes) { + for (const [key, value] of Object.entries(attributes)) { + node.setAttribute(key, String(value)); + } + } + for (const child of children) node.appendChild(child); + return node; +} + +/** + * @param {string} value + * @returns {number[]} + */ +function parseColor(value) { + const hex = value.trim(); + if (hex.startsWith('#')) { + const full = hex.length === 4 + ? hex + .slice(1) + .split('') + .map((character) => character + character) + .join('') + : hex.slice(1); + return [ + Number.parseInt(full.slice(0, 2), 16), + Number.parseInt(full.slice(2, 4), 16), + Number.parseInt(full.slice(4, 6), 16), + ]; + } + const match = hex.match(/rgba?\(([^)]+)\)/); + if (match) { + const parts = match[1].split(',').map((part) => Number.parseFloat(part.trim())); + return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]; + } + return [0, 0, 0]; +} + +/** + * @param {number[]} low + * @param {number[]} high + * @param {number} ratio + * @returns {string} + */ +function mixColor(low, high, ratio) { + const channel = (index) => Math.round(low[index] + (high[index] - low[index]) * ratio); + return `rgb(${channel(0)}, ${channel(1)}, ${channel(2)})`; +} + +/** + * @param {string} color + * @returns {string} + */ +function readableTextOn(color) { + const [red, green, blue] = parseColor(color); + const luminance = (0.299 * red + 0.587 * green + 0.114 * blue) / 255; + return luminance > 0.6 ? '#171717' : '#ffffff'; +} + +/** + * @param {string} message + * @param {number} [duration] + */ +function showToast(message, duration = 4000) { + elements.toast.textContent = message; + elements.toast.hidden = false; + window.clearTimeout(showToast.timer); + showToast.timer = window.setTimeout(() => { + elements.toast.hidden = true; + }, duration); +} + +/* ------------------------------------------------------------ data loading */ + +async function requestJson(url, options = {}) { + const response = await fetch(url, options); + const payload = await response.json().catch(() => null); + if (!response.ok) { + const error = new Error( + payload?.message ?? `La solicitud falló con el estado ${response.status}.`, + ); + error.details = payload?.details ?? []; + throw error; + } + return payload; +} + +async function loadDataset() { + elements.loading.hidden = false; + elements.dashboard.hidden = true; + elements.errorBanner.hidden = true; + try { + const dataset = await requestJson('/api/dataset'); + state.dataset = dataset; + elements.loading.hidden = true; + elements.dashboard.hidden = false; + syncPeriodInput(dataset); + applyPeriodLabels(dataset); + elements.sourceSummary.textContent = describeSource(dataset); + populateFilters(dataset); + render(); + } catch (error) { + elements.loading.hidden = true; + elements.dashboard.hidden = true; + elements.errorMessage.textContent = `No se pudieron cargar las evaluaciones: ${error.message}`; + elements.errorBanner.hidden = false; + } +} + +/** + * @param {object} dataset + * @returns {string} + */ +function describeSource(dataset) { + const meta = dataset.meta; + return [ + `Fuente: ${meta.sourceLabel ?? meta.sourceFile}`, + `${meta.courses} cursos`, + `${meta.teachers} docentes`, + `${meta.records} evaluaciones (${meta.courses} × ${meta.items} reactivos)`, + `${meta.comments} comentarios`, + state.period ? `periodo ${state.period}` : 'periodo actual', + ].join(' · '); +} + +/** + * Show the period of the loaded file wherever the interface mentions it. + * @param {object} dataset + */ +function applyPeriodLabels(dataset) { + const meta = dataset.meta ?? {}; + const period = meta.evaluationPeriod || state.periodTyped.trim(); + const label = period ? `Promedio ${period}` : meta.currentLabel || 'Promedio'; + elements.kpiCurrentLabel.textContent = label; + elements.hintTeachers.textContent = + `${label} de los reactivos evaluados; la marca indica el promedio histórico del docente ` + + 'y la cifra de la derecha, la participación de sus alumnos.'; + elements.hintItems.textContent = + `Perfil del instrumento de ${meta.items ?? 17} reactivos: ${label} frente al histórico.`; + elements.heatmapCaption.textContent = `${label} de cada reactivo en cada curso seleccionado`; + state.period = period; + state.currentLabel = label; +} + +/** + * Show the period of the loaded file, unless the user has renamed it. + * @param {object} dataset + */ +function syncPeriodInput(dataset) { + const meta = dataset.meta ?? {}; + const filePeriod = (meta.evaluationPeriod || '').trim(); + if (filePeriod) { + elements.periodInput.value = filePeriod; + elements.periodInput.disabled = true; + if (elements.periodHint) { + elements.periodHint.textContent = 'El archivo ya nombra el período'; + } + } else { + elements.periodInput.value = state.periodTyped; + elements.periodInput.disabled = false; + if (elements.periodHint) { + elements.periodHint.textContent = 'Solo renombra las etiquetas del tablero'; + } + } + elements.periodInput.placeholder = 'sin período'; +} + +/** + * Groups of the selection, counted per (curso, docente). + * + * A course can be split between several teachers, each one with their own + * group of students, so participation is counted per group and not per course. + * + * @param {object[]} records + * @returns {{ course: string, teacher: string, participants: number, convened: number, percent: number | null, declared: number | null }[]} + */ +function participationGroups(records) { + const dataset = state.dataset; + const groups = new Map(); + for (const record of records) { + const key = `${record.course}\u0000${record.teacher}`; + if (groups.has(key)) continue; + const course = dataset.courses.find((entry) => entry.id === record.course); + const group = course?.groups.find( + (entry) => (entry.teacher || '(sin docente)') === (record.teacher || '(sin docente)'), + ); + groups.set(key, { + course: record.course, + teacher: record.teacher, + participants: group?.participants ?? record.participants, + convened: group?.convened ?? record.convened, + percent: group?.participationPercent ?? null, + declared: group?.participationPercentDeclared ?? null, + }); + } + return [...groups.values()]; +} + +/** + * Participation of a set of groups, weighted by the number of summoned students. + * @param {{ participants: number, convened: number, percent: number | null }[]} groups + * @returns {number | null} + */ +function weightedParticipation(groups) { + const usable = groups.filter((group) => group.percent !== null && group.convened > 0); + if (usable.length === 0) { + const participants = groups.reduce((total, group) => total + group.participants, 0); + const convened = groups.reduce((total, group) => total + group.convened, 0); + return convened > 0 ? (participants / convened) * 100 : null; + } + const denominator = usable.reduce((total, group) => total + group.convened, 0); + const numerator = usable.reduce((total, group) => total + group.percent * group.convened, 0); + return denominator > 0 ? numerator / denominator : null; +} + +/* ----------------------------------------------------------------- filters */ + +function populateFilters(dataset) { + const terms = [...new Set(dataset.courses.map((course) => course.term))].sort((left, right) => + left.localeCompare(right, 'es'), + ); + const specialties = [...new Set(dataset.courses.map((course) => course.specialty))].sort((left, right) => + left.localeCompare(right, 'es'), + ); + + fillSelect(elements.filterTerm, 'Todos los períodos', terms, (value) => value); + fillSelect(elements.filterSpecialty, 'Todas las maestrías', specialties, (value) => value); + fillSelect( + elements.filterTeacher, + 'Todos los docentes', + dataset.teachers, + (value) => value, + ); + fillSelect( + elements.filterItem, + 'Los 17 reactivos', + dataset.items.map((item) => ({ value: String(item.id), label: `${item.id}. ${item.text}` })), + (option) => option.value, + ); +} + +/** + * @param {HTMLSelectElement} select + * @param {string} allLabel + * @param {Array<{ value: string, label: string } | string>} options + * @param {(option: any) => string} valueOf + */ +function fillSelect(select, allLabel, options, valueOf) { + const previous = select.value; + select.replaceChildren(); + const all = document.createElement('option'); + all.value = 'all'; + all.textContent = allLabel; + select.appendChild(all); + for (const option of options) { + const element = document.createElement('option'); + element.value = valueOf(option); + element.textContent = typeof option === 'string' ? option : option.label; + select.appendChild(element); + } + select.value = [...select.options].some((option) => option.value === previous) ? previous : 'all'; +} + +/** + * @returns {object[]} + */ +function filteredRecords() { + const dataset = state.dataset; + if (!dataset) return []; + const text = normalizeText(state.filters.text); + return dataset.records.filter((record) => { + if (state.filters.term !== 'all' && record.term !== state.filters.term) return false; + if (state.filters.item !== 'all' && String(record.item) !== state.filters.item) return false; + const course = dataset.courses.find((entry) => entry.id === record.course); + if (!course) return false; + if (state.filters.specialty !== 'all' && course.specialty !== state.filters.specialty) return false; + if (state.filters.teacher !== 'all' && record.teacher !== state.filters.teacher) return false; + if (text) { + const haystack = normalizeText( + [ + record.teacher, + record.course, + course.subject, + course.program, + course.specialty, + record.term, + record.comments.join(' '), + ].join(' '), + ); + if (!haystack.includes(text)) return false; + } + return true; + }); +} + +/* ------------------------------------------------------------- aggregation */ + +/** + * @param {object[]} records + * @returns {object} + */ +function summarize(records) { + const withHistory = records.filter((record) => record.historical !== null); + const historicalValues = withHistory.map((record) => record.historical); + const currentWithHistory = withHistory.map((record) => record.current); + return { + count: records.length, + current: mean(records.map((record) => record.current)), + historical: mean(historicalValues), + historicalCount: withHistory.length, + delta: + withHistory.length === 0 + ? null + : mean(currentWithHistory) - mean(historicalValues), + }; +} + +/** + * @param {object[]} records + * @param {(record: object) => string} keyOf + * @returns {Map} + */ +function groupBy(records, keyOf) { + const groups = new Map(); + for (const record of records) { + const key = keyOf(record); + const list = groups.get(key); + if (list) list.push(record); + else groups.set(key, [record]); + } + return groups; +} + +/* ------------------------------------------------------------------ render */ + +function render() { + if (!state.dataset) return; + const records = filteredRecords(); + renderChips(); + elements.dashboard.hidden = false; + + if (records.length === 0) { + elements.dashboardContent.hidden = true; + elements.emptyState.hidden = false; + return; + } + + elements.dashboardContent.hidden = false; + elements.emptyState.hidden = true; + + renderKpis(records); + renderTeacherChart(records); + renderGroupChart(elements.chartTerms, groupBy(records, (record) => record.term), 'Período'); + renderGroupChart( + elements.chartSpecialties, + groupBy(records, (record) => courseOf(record.course).specialty), + 'Maestría', + ); + renderItemChart(records); + renderHeatmap(records); + renderComments(records); + renderNotes(records); + renderMethod(); +} + +function renderChips() { + const chips = []; + const labels = { + term: 'Período', + specialty: 'Maestría', + teacher: 'Docente', + item: 'Reactivo', + }; + for (const [key, label] of Object.entries(labels)) { + if (state.filters[key] === 'all') continue; + chips.push({ key, label, value: state.filters[key] }); + } + if (state.filters.text.trim()) { + chips.push({ key: 'text', label: 'Búsqueda', value: state.filters.text.trim() }); + } + + elements.activeFilters.replaceChildren(); + for (const chip of chips) { + const element = document.createElement('span'); + element.className = 'chip'; + const text = document.createElement('span'); + text.textContent = `${chip.label}: ${chip.value}`; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.setAttribute('aria-label', `Quitar el filtro ${chip.label}`); + remove.textContent = '×'; + remove.addEventListener('click', () => { + state.filters[chip.key] = chip.key === 'text' ? '' : 'all'; + syncFilterControls(); + render(); + saveViewState(); + }); + element.append(text, remove); + elements.activeFilters.appendChild(element); + } +} + +/** + * @param {object[]} records + */ +function renderKpis(records) { + const summary = summarize(records); + elements.kpiCurrent.textContent = formatScore(summary.current); + elements.kpiCurrentDetail.textContent = + `Media de ${numberFormat.format(summary.count)} evaluaciones` + + (state.period ? ` ${state.period}` : ''); + + elements.kpiDelta.textContent = formatDelta(summary.delta); + elements.kpiDelta.classList.toggle('kpi__value--up', summary.delta !== null && summary.delta > 0); + elements.kpiDelta.classList.toggle('kpi__value--down', summary.delta !== null && summary.delta < 0); + if (summary.historicalCount === 0) { + elements.kpiDeltaDetail.textContent = 'Ningún registro de la selección tiene línea base histórica.'; + } else { + elements.kpiDeltaDetail.textContent = `${formatScore(summary.current)} frente a ${formatScore( + summary.historical, + )} histórico en ${numberFormat.format(summary.historicalCount)} registros con base.`; + } + + const courseIds = [...new Set(records.map((record) => record.course))]; + const courses = courseIds.map((courseId) => courseOf(courseId)); + const groups = participationGroups(records); + const participants = groups.reduce((total, group) => total + group.participants, 0); + const convened = groups.reduce((total, group) => total + group.convened, 0); + const rate = weightedParticipation(groups); + elements.kpiParticipation.textContent = rate === null ? '—' : `${rate.toFixed(1)} %`; + const mixed = courses.filter((course) => !course.participationStable); + const split = groups.length > courses.length; + elements.kpiParticipationDetail.textContent = + `${numberFormat.format(participants)} de ${numberFormat.format(convened)} convocados en ` + + `${numberFormat.format(courses.length)} cursos` + + (split ? ` · ${numberFormat.format(groups.length)} grupos de docente` : '') + + (mixed.length > 0 ? ` · ${mixed.length} con participación mixta` : ''); + + const comments = records.flatMap((record) => record.comments); + elements.kpiComments.textContent = numberFormat.format(comments.length); + const coursesWithComments = new Set( + records.filter((record) => record.comments.length > 0).map((record) => record.course), + ); + elements.kpiCommentsDetail.textContent = + comments.length === 0 + ? 'Sin comentarios libres en la selección.' + : `En ${numberFormat.format(coursesWithComments.size)} de ${numberFormat.format( + courses.length, + )} cursos de la selección.`; +} + +/** + * @param {string} courseId + * @returns {object} + */ +function courseOf(courseId) { + return state.dataset.courses.find((course) => course.id === courseId); +} + +/** + * @param {object[]} records + */ +function renderTeacherChart(records) { + const groups = groupBy(records, (record) => record.teacher); + const groupsByTeacher = new Map(); + for (const group of participationGroups(records)) { + const list = groupsByTeacher.get(group.teacher) ?? []; + list.push(group); + groupsByTeacher.set(group.teacher, list); + } + const rows = [...groups.entries()] + .map(([teacher, teacherRecords]) => ({ + label: teacher, + summary: summarize(teacherRecords), + participation: weightedParticipation(groupsByTeacher.get(teacher) ?? []), + })) + .sort((left, right) => (right.summary.current ?? 0) - (left.summary.current ?? 0)); + + const container = elements.chartTeachers; + container.replaceChildren(); + if (rows.length === 0) { + container.appendChild(emptyBlock('Sin docentes en la selección.')); + return; + } + + const legend = document.createElement('div'); + legend.className = 'chart__legend'; + legend.append( + legendItem(state.currentLabel, false), + legendItem('Promedio histórico', true), + legendItem('Participación de alumnos', null, true), + legendItem('Eje ajustado al rango de los valores', null, true), + ); + container.appendChild(legend); + + const width = 760; + const labelWidth = 240; + const valueWidth = 132; + const rowHeight = 26; + const height = rows.length * rowHeight + 34; + const plotWidth = width - labelWidth - valueWidth; + const values = rows.flatMap((row) => [row.summary.current, row.summary.historical]).filter( + (value) => value !== null && Number.isFinite(value), + ); + const rawMin = Math.min(...values); + const rawMax = Math.max(...values); + const pad = Math.max((rawMax - rawMin) * 0.12, 0.05); + const domainMin = clamp(rawMin - pad, SCALE_MIN, SCALE_MAX); + const domainMax = clamp(rawMax + pad, domainMin + 0.1, SCALE_MAX); + const scale = (value) => + labelWidth + ((value - domainMin) / (domainMax - domainMin)) * plotWidth; + + const svg = svgElement('svg', { + viewBox: `0 0 ${width} ${height}`, + role: 'img', + 'aria-label': `Promedio por docente, ${rows.length} docentes`, + }); + + for (const tick of [domainMin, (domainMin + domainMax) / 2, domainMax]) { + const x = scale(tick); + svg.appendChild( + svgElement('line', { + class: 'chart__grid', + x1: x, + x2: x, + y1: 0, + y2: height - 24, + }), + ); + const label = svgElement('text', { + class: 'chart__label', + x, + y: height - 8, + 'text-anchor': 'middle', + }); + label.textContent = tick.toFixed(1); + svg.appendChild(label); + } + + rows.forEach((row, index) => { + const y = index * rowHeight + 6; + const barHeight = 12; + + const name = svgElement('text', { + class: 'chart__label', + x: labelWidth - 10, + y: y + barHeight - 2, + 'text-anchor': 'end', + }); + name.textContent = row.label.length > 34 ? `${row.label.slice(0, 33)}…` : row.label; + const title = svgElement('title'); + title.textContent = + `${row.label}: ${formatScore(row.summary.current)} (${row.summary.count} evaluaciones)` + + (row.participation !== null ? ` · participación ${row.participation.toFixed(1)} %` : ''); + name.appendChild(title); + svg.appendChild(name); + + const bar = svgElement('rect', { + class: 'chart__bar chart__bar--interactive', + x: labelWidth, + y, + width: Math.max(scale(row.summary.current) - labelWidth, 1), + height: barHeight, + rx: 3, + }); + const barTitle = svgElement('title'); + barTitle.textContent = `${row.label}: ${state.currentLabel} ${formatScore(row.summary.current)}`; + bar.appendChild(barTitle); + bar.addEventListener('click', () => { + state.filters.teacher = row.label; + syncFilterControls(); + render(); + saveViewState(); + }); + svg.appendChild(bar); + + if (row.summary.historical !== null) { + const markerX = scale(row.summary.historical); + svg.appendChild( + svgElement('line', { + class: 'chart__marker', + x1: markerX, + x2: markerX, + y1: y - 3, + y2: y + barHeight + 3, + }), + ); + const markerTitle = svgElement('title'); + markerTitle.textContent = `Promedio histórico ${formatScore(row.summary.historical)}`; + svg.appendChild(markerTitle); + } + + if (row.participation !== null) { + const participation = svgElement('text', { + class: 'chart__meta', + x: width - 76, + y: y + barHeight - 2, + 'text-anchor': 'end', + }); + participation.textContent = `${row.participation.toFixed(0)} %`; + const participationTitle = svgElement('title'); + participationTitle.textContent = `Participación de alumnos: ${row.participation.toFixed(1)} %`; + participation.appendChild(participationTitle); + svg.appendChild(participation); + } + + const value = svgElement('text', { + class: 'chart__value', + x: width - 8, + y: y + barHeight - 2, + 'text-anchor': 'end', + }); + value.textContent = formatScore(row.summary.current); + svg.appendChild(value); + }); + + container.appendChild(svg); +} + +/** + * @param {object[]} records + * @param {Map} groups + * @param {string} label + */ +function renderGroupChart(container, groups, label) { + container.replaceChildren(); + const rows = [...groups.entries()] + .map(([name, groupRecords]) => ({ name, summary: summarize(groupRecords) })) + .sort((left, right) => (right.summary.current ?? 0) - (left.summary.current ?? 0)); + + if (rows.length === 0) { + container.appendChild(emptyBlock(`Sin ${label.toLowerCase()} en la selección.`)); + return; + } + + const legend = document.createElement('div'); + legend.className = 'chart__legend'; + legend.append(legendItem(state.currentLabel, false), legendItem('Promedio histórico', true)); + container.appendChild(legend); + + const width = 760; + const height = 250; + const padding = { top: 16, right: 16, bottom: 52, left: 46 }; + const plotWidth = width - padding.left - padding.right; + const plotHeight = height - padding.top - padding.bottom; + + const values = rows + .flatMap((row) => [row.summary.current, row.summary.historical]) + .filter((value) => value !== null && Number.isFinite(value)); + const rawMin = Math.min(...values); + const rawMax = Math.max(...values); + const pad = Math.max((rawMax - rawMin) * 0.2, 0.1); + const domainMin = clamp(rawMin - pad, SCALE_MIN, SCALE_MAX); + const domainMax = clamp(rawMax + pad, domainMin + 0.2, SCALE_MAX); + const yScale = (value) => + padding.top + plotHeight - ((value - domainMin) / (domainMax - domainMin)) * plotHeight; + + const svg = svgElement('svg', { + viewBox: `0 0 ${width} ${height}`, + role: 'img', + 'aria-label': `Comparación por ${label.toLowerCase()}`, + }); + + for (const tick of [domainMin, (domainMin + domainMax) / 2, domainMax]) { + const y = yScale(tick); + svg.appendChild( + svgElement('line', { class: 'chart__grid', x1: padding.left, x2: width - padding.right, y1: y, y2: y }), + ); + const labelNode = svgElement('text', { + class: 'chart__label', + x: padding.left - 8, + y: y + 4, + 'text-anchor': 'end', + }); + labelNode.textContent = tick.toFixed(1); + svg.appendChild(labelNode); + } + + const groupWidth = plotWidth / rows.length; + const barWidth = Math.min(34, groupWidth / 3); + + rows.forEach((row, index) => { + const center = padding.left + groupWidth * index + groupWidth / 2; + const currentX = center - barWidth - 3; + const historicalX = center + 3; + + const currentBar = svgElement('rect', { + class: 'chart__bar', + x: currentX, + y: yScale(row.summary.current), + width: barWidth, + height: Math.max(padding.top + plotHeight - yScale(row.summary.current), 1), + rx: 3, + }); + const title = svgElement('title'); + title.textContent = `${row.name}: ${state.currentLabel} ${formatScore(row.summary.current)} (${row.summary.count} evaluaciones)`; + currentBar.appendChild(title); + svg.appendChild(currentBar); + + if (row.summary.historical !== null) { + const historicalBar = svgElement('rect', { + class: 'chart__bar chart__bar--historical', + x: historicalX, + y: yScale(row.summary.historical), + width: barWidth, + height: Math.max(padding.top + plotHeight - yScale(row.summary.historical), 1), + rx: 3, + }); + const historicalTitle = svgElement('title'); + historicalTitle.textContent = `${row.name}: histórico ${formatScore(row.summary.historical)}`; + historicalBar.appendChild(historicalTitle); + svg.appendChild(historicalBar); + } + + const currentValue = svgElement('text', { + class: 'chart__value', + x: currentX + barWidth / 2, + y: yScale(row.summary.current) - 6, + 'text-anchor': 'middle', + }); + currentValue.textContent = formatScore(row.summary.current, 1); + svg.appendChild(currentValue); + + const name = svgElement('text', { + class: 'chart__label', + x: center, + y: height - 30, + 'text-anchor': 'middle', + }); + name.textContent = row.name.length > 22 ? `${row.name.slice(0, 21)}…` : row.name; + const nameTitle = svgElement('title'); + nameTitle.textContent = row.name; + name.appendChild(nameTitle); + svg.appendChild(name); + + const count = svgElement('text', { + class: 'chart__label', + x: center, + y: height - 14, + 'text-anchor': 'middle', + }); + count.textContent = `${row.summary.count} eval.`; + svg.appendChild(count); + }); + + svg.appendChild( + svgElement('line', { + class: 'chart__axis', + x1: padding.left, + x2: width - padding.right, + y1: padding.top + plotHeight, + y2: padding.top + plotHeight, + }), + ); + + container.appendChild(svg); +} + +/** + * @param {object[]} records + */ +function renderItemChart(records) { + const container = elements.chartItems; + container.replaceChildren(); + const groups = groupBy(records, (record) => String(record.item)); + const rows = [...groups.entries()] + .map(([item, itemRecords]) => ({ item: Number(item), summary: summarize(itemRecords) })) + .sort((left, right) => left.item - right.item); + + if (rows.length === 0) { + container.appendChild(emptyBlock('Sin reactivos en la selección.')); + return; + } + + const legend = document.createElement('div'); + legend.className = 'chart__legend'; + legend.append(legendItem(state.currentLabel, false), legendItem('Promedio histórico', true)); + container.appendChild(legend); + + const width = 900; + const height = 300; + const padding = { top: 18, right: 16, bottom: 56, left: 46 }; + const plotWidth = width - padding.left - padding.right; + const plotHeight = height - padding.top - padding.bottom; + + const values = rows + .flatMap((row) => [row.summary.current, row.summary.historical]) + .filter((value) => value !== null && Number.isFinite(value)); + const rawMin = Math.min(...values); + const rawMax = Math.max(...values); + const pad = Math.max((rawMax - rawMin) * 0.25, 0.15); + const domainMin = clamp(rawMin - pad, SCALE_MIN, SCALE_MAX); + const domainMax = clamp(rawMax + pad, domainMin + 0.25, SCALE_MAX); + const yScale = (value) => + padding.top + plotHeight - ((value - domainMin) / (domainMax - domainMin)) * plotHeight; + + const svg = svgElement('svg', { + viewBox: `0 0 ${width} ${height}`, + role: 'img', + 'aria-label': 'Promedio por reactivo del instrumento', + }); + + for (const tick of [domainMin, (domainMin + domainMax) / 2, domainMax]) { + const y = yScale(tick); + svg.appendChild( + svgElement('line', { class: 'chart__grid', x1: padding.left, x2: width - padding.right, y1: y, y2: y }), + ); + const labelNode = svgElement('text', { + class: 'chart__label', + x: padding.left - 8, + y: y + 4, + 'text-anchor': 'end', + }); + labelNode.textContent = tick.toFixed(1); + svg.appendChild(labelNode); + } + + const groupWidth = plotWidth / rows.length; + const barWidth = Math.max(Math.min(groupWidth / 3.2, 26), 5); + + rows.forEach((row, index) => { + const center = padding.left + groupWidth * index + groupWidth / 2; + const currentX = center - barWidth - 1.5; + const historicalX = center + 1.5; + const itemText = state.dataset.items.find((item) => item.id === row.item)?.text ?? ''; + + const currentBar = svgElement('rect', { + class: 'chart__bar', + x: currentX, + y: yScale(row.summary.current), + width: barWidth, + height: Math.max(padding.top + plotHeight - yScale(row.summary.current), 1), + rx: 2, + }); + const title = svgElement('title'); + title.textContent = `Reactivo ${row.item}: ${itemText} — ${state.currentLabel} ${formatScore(row.summary.current)}`; + currentBar.appendChild(title); + svg.appendChild(currentBar); + + if (row.summary.historical !== null) { + const historicalBar = svgElement('rect', { + class: 'chart__bar chart__bar--historical', + x: historicalX, + y: yScale(row.summary.historical), + width: barWidth, + height: Math.max(padding.top + plotHeight - yScale(row.summary.historical), 1), + rx: 2, + }); + const historicalTitle = svgElement('title'); + historicalTitle.textContent = `Reactivo ${row.item}: histórico ${formatScore(row.summary.historical)}`; + historicalBar.appendChild(historicalTitle); + svg.appendChild(historicalBar); + } + + const labelNode = svgElement('text', { + class: 'chart__label', + x: center, + y: height - 34, + 'text-anchor': 'middle', + }); + labelNode.textContent = String(row.item); + svg.appendChild(labelNode); + + const labelTitle = svgElement('title'); + labelTitle.textContent = `${row.item}. ${itemText}`; + labelNode.appendChild(labelTitle); + }); + + svg.appendChild( + svgElement('line', { + class: 'chart__axis', + x1: padding.left, + x2: width - padding.right, + y1: padding.top + plotHeight, + y2: padding.top + plotHeight, + }), + ); + + container.appendChild(svg); +} + +/** + * @param {object[]} records + */ +function renderHeatmap(records) { + const dataset = state.dataset; + const table = elements.heatmap; + table.replaceChildren(); + + const courses = [...new Set(records.map((record) => record.course))] + .map((courseId) => courseOf(courseId)) + .sort((left, right) => left.id.localeCompare(right.id)); + const items = dataset.items; + const values = records.map((record) => record.current); + const min = Math.min(...values); + const max = Math.max(...values); + const styles = getComputedStyle(document.documentElement); + const low = parseColor(styles.getPropertyValue('--chart-scale-low')); + const high = parseColor(styles.getPropertyValue('--chart-scale-high')); + + const head = document.createElement('thead'); + const headRow = document.createElement('tr'); + const corner = document.createElement('th'); + corner.scope = 'col'; + corner.textContent = 'Curso'; + headRow.appendChild(corner); + for (const item of items) { + const cell = document.createElement('th'); + cell.scope = 'col'; + cell.textContent = String(item.id); + const title = document.createElement('span'); + title.className = 'visually-hidden'; + title.textContent = item.text; + cell.appendChild(title); + headRow.appendChild(cell); + } + head.appendChild(headRow); + table.appendChild(head); + + const body = document.createElement('tbody'); + for (const course of courses) { + const row = document.createElement('tr'); + const rowHeader = document.createElement('th'); + rowHeader.scope = 'row'; + rowHeader.textContent = `${course.id} · ${course.teacher}`; + rowHeader.title = `${course.id} · ${course.subject}`; + row.appendChild(rowHeader); + + for (const item of items) { + const record = records.find( + (entry) => entry.course === course.id && entry.item === item.id, + ); + const cell = document.createElement('td'); + if (!record) { + cell.textContent = '·'; + cell.setAttribute('aria-label', `${course.id}, reactivo ${item.id}: sin datos`); + } else { + const ratio = max === min ? 0.5 : (record.current - min) / (max - min); + const background = mixColor(low, high, ratio); + cell.style.background = background; + cell.style.color = readableTextOn(background); + cell.textContent = record.current.toFixed(1); + const label = document.createElement('span'); + label.className = 'visually-hidden'; + label.textContent = `Promedio ${record.current.toFixed(2)}`; + cell.appendChild(label); + cell.setAttribute( + 'aria-label', + `${course.id}, reactivo ${item.id}: promedio ${record.current.toFixed(2)}`, + ); + cell.tabIndex = 0; + cell.addEventListener('click', () => openCourseDetail(course.id)); + cell.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + openCourseDetail(course.id); + } + }); + } + row.appendChild(cell); + } + body.appendChild(row); + } + table.appendChild(body); + + elements.matrixScaleMin.textContent = formatScore(min, 1); + elements.matrixScaleMax.textContent = formatScore(max, 1); +} + +/** + * @param {object[]} records + */ +function renderComments(records) { + const container = elements.commentsList; + container.replaceChildren(); + const comments = records.flatMap((record) => + record.comments.map((text) => ({ text, record })), + ); + + if (comments.length === 0) { + container.appendChild(emptyBlock('No hay comentarios libres en la selección actual.')); + return; + } + + for (const comment of comments) { + const course = courseOf(comment.record.course); + const element = document.createElement('article'); + element.className = 'comment'; + + const meta = document.createElement('div'); + meta.className = 'comment__meta'; + const tag = document.createElement('span'); + tag.className = 'comment__tag'; + tag.textContent = comment.record.course; + const teacher = document.createElement('span'); + teacher.textContent = course?.teacher ?? comment.record.teacher; + const item = document.createElement('span'); + item.textContent = `Reactivo ${comment.record.item}`; + const term = document.createElement('span'); + term.textContent = course?.term ?? ''; + meta.append(tag, teacher, item, term); + + const text = document.createElement('p'); + text.className = 'comment__text'; + text.textContent = comment.text; + + element.append(meta, text); + container.appendChild(element); + } +} + +/** + * @param {object[]} records + */ +function renderNotes(records) { + const dataset = state.dataset; + const list = elements.dataNotes; + list.replaceChildren(); + + const notes = [...dataset.notes]; + const courseIds = [...new Set(records.map((record) => record.course))]; + const withoutHistory = courseIds.filter((courseId) => !courseOf(courseId).historicalAvailable); + if (withoutHistory.length > 0 && courseIds.length < dataset.courses.length) { + notes.push({ + id: 'seleccion-sin-historico', + tone: 'neutral', + text: `En la selección actual, ${withoutHistory.length} de ${courseIds.length} cursos no tienen línea base histórica (${withoutHistory.join( + ', ', + )}).`, + }); + } + + for (const note of notes) { + const item = document.createElement('li'); + item.className = note.tone === 'warning' ? 'note note--warning' : 'note'; + const badge = document.createElement('span'); + badge.className = 'note__badge'; + badge.textContent = note.tone === 'warning' ? 'Revisar' : 'Dato'; + const text = document.createElement('span'); + text.textContent = note.text; + item.append(badge, text); + list.appendChild(item); + } +} + +function renderMethod() { + const list = elements.methodNotes; + list.replaceChildren(); + const entries = [ + [ + state.currentLabel, + 'Media aritmética de los promedios de cada reactivo (uno por curso y reactivo), sin ponderar por número de respuestas.', + ], + [ + 'Diferencia vs. histórico', + `Se calcula solo sobre los registros que tienen línea base histórica: ${state.currentLabel} menos el promedio histórico de ese mismo subconjunto.`, + ], + [ + 'Participación', + 'Se cuenta por grupo de (curso, docente), de modo que un curso dividido entre varios docentes conserva los grupos de alumnos de cada uno; se toma el valor del primer reactivo de cada grupo. Si el archivo trae una columna de participación por docente, ese valor se usa en lugar del calculado.', + ], + [ + 'Filtros cruzados', + 'Período, maestría, docente, reactivo y búsqueda de texto se aplican a la vez y recalculan todos los cortes.', + ], + [ + 'Escala', + 'La evaluación usa una escala de 0 a 10; los ejes de las gráficas se ajustan al rango de los valores mostrados.', + ], + ]; + for (const [term, description] of entries) { + const dt = document.createElement('dt'); + dt.textContent = term; + const dd = document.createElement('dd'); + dd.textContent = description; + list.append(dt, dd); + } +} + +/** + * @param {string} text + * @param {boolean} [historical] + * @param {boolean} [plain] + * @returns {HTMLElement} + */ +function legendItem(text, historical = false, plain = false) { + const item = document.createElement('span'); + item.className = 'chart__legend-item'; + if (!plain) { + const swatch = document.createElement('span'); + swatch.className = historical ? 'chart__swatch chart__swatch--historical' : 'chart__swatch'; + item.appendChild(swatch); + } + const label = document.createElement('span'); + label.textContent = text; + item.appendChild(label); + return item; +} + +/** + * @param {string} text + * @returns {HTMLElement} + */ +function emptyBlock(text) { + const block = document.createElement('p'); + block.className = 'chart__empty'; + block.textContent = text; + return block; +} + +/* ------------------------------------------------------------ course detail */ + +function openCourseDetail(courseId) { + const dataset = state.dataset; + const course = courseOf(courseId); + if (!course) return; + const records = dataset.records.filter((record) => record.course === courseId); + + elements.dialogTitle.textContent = `${course.id} · ${course.subject || 'Curso sin materia'}`; + elements.dialogSubtitle.textContent = [ + course.teacher, + course.specialty, + course.term, + course.program, + ] + .filter(Boolean) + .join(' · '); + + const body = elements.dialogBody; + body.replaceChildren(); + + const facts = document.createElement('div'); + facts.className = 'detail__facts'; + const factEntries = [ + ['Docente', course.teachers.join(' + ')], + [ + 'Participación', + course.groups.length > 1 + ? course.groups + .map( + (group) => + `${group.teacherLabel}: ${group.participants} de ${group.convened}` + + (group.participationPercent !== null ? ` (${group.participationPercent} %)` : ''), + ) + .join(' · ') + : `${course.participants} de ${course.convened} convocados` + + (course.participationPercent !== null ? ` (${course.participationPercent} %)` : ''), + ], + ['Línea base histórica', course.historicalAvailable ? 'Disponible' : 'No disponible'], + ['Comentarios', numberFormat.format(course.commentCount)], + ]; + if (!course.participationStable) { + factEntries.push([ + 'Participación por reactivo', + course.participationVariants + .map((variant) => `${variant.participants}/${variant.convened} en ${variant.items} reactivos`) + .join(' · '), + ]); + } + for (const [label, value] of factEntries) { + const fact = document.createElement('div'); + fact.className = 'fact'; + const factLabel = document.createElement('p'); + factLabel.className = 'fact__label'; + factLabel.textContent = label; + const factValue = document.createElement('p'); + factValue.className = 'fact__value'; + factValue.textContent = value; + fact.append(factLabel, factValue); + facts.appendChild(fact); + } + body.appendChild(facts); + + const table = document.createElement('table'); + const caption = document.createElement('caption'); + caption.className = 'visually-hidden'; + caption.textContent = `Detalle de los 17 reactivos del curso ${course.id}`; + const head = document.createElement('thead'); + const headRow = document.createElement('tr'); + for (const [label, numeric] of [ + ['Reactivo', false], + ['Texto del reactivo', false], + [state.period || 'Promedio', true], + [dataset.meta.historicalLabel ?? 'Histórico', true], + ['Δ', true], + ]) { + const cell = document.createElement('th'); + cell.scope = 'col'; + if (numeric) cell.className = 'numeric'; + cell.textContent = label; + headRow.appendChild(cell); + } + head.appendChild(headRow); + table.appendChild(head); + + const tbody = document.createElement('tbody'); + for (const record of records.sort((left, right) => left.item - right.item)) { + const item = dataset.items.find((entry) => entry.id === record.item); + const row = document.createElement('tr'); + const number = document.createElement('td'); + number.textContent = String(record.item); + const text = document.createElement('td'); + text.textContent = item?.text ?? ''; + const current = document.createElement('td'); + current.className = 'numeric'; + current.textContent = formatScore(record.current); + const historical = document.createElement('td'); + historical.className = 'numeric'; + historical.textContent = record.historical === null ? '—' : formatScore(record.historical); + const delta = document.createElement('td'); + delta.className = 'numeric'; + if (record.historical === null) { + delta.textContent = '—'; + } else { + const value = record.current - record.historical; + delta.textContent = formatDelta(value); + if (value > 0) delta.classList.add('delta--up'); + else if (value < 0) delta.classList.add('delta--down'); + } + row.append(number, text, current, historical, delta); + tbody.appendChild(row); + } + table.appendChild(tbody); + body.appendChild(table); + + const courseComments = records.flatMap((record) => + record.comments.map((text) => ({ text, item: record.item })), + ); + if (courseComments.length > 0) { + const title = document.createElement('h3'); + title.className = 'detail__section-title'; + title.textContent = `Comentarios (${courseComments.length})`; + body.appendChild(title); + const list = document.createElement('div'); + list.className = 'comments'; + for (const comment of courseComments) { + const element = document.createElement('article'); + element.className = 'comment'; + const meta = document.createElement('div'); + meta.className = 'comment__meta'; + const tag = document.createElement('span'); + tag.className = 'comment__tag'; + tag.textContent = `Reactivo ${comment.item}`; + meta.appendChild(tag); + const text = document.createElement('p'); + text.className = 'comment__text'; + text.textContent = comment.text; + element.append(meta, text); + list.appendChild(element); + } + body.appendChild(list); + } + + if (typeof elements.dialog.showModal === 'function') { + elements.dialog.showModal(); + } else { + elements.dialog.setAttribute('open', ''); + } +} + +/* ------------------------------------------------------------------ import */ + +async function importWorkbook(file) { + elements.fileInput.disabled = true; + elements.resetData.disabled = true; + try { + const buffer = await file.arrayBuffer(); + const dataset = await requestJson('/api/import', { + method: 'POST', + headers: { 'content-type': 'application/octet-stream' }, + body: buffer, + }); + state.dataset = dataset; + state.filters = { term: 'all', specialty: 'all', teacher: 'all', item: 'all', text: '' }; + syncFilterControls(); + syncPeriodInput(dataset); + applyPeriodLabels(dataset); + elements.sourceSummary.textContent = describeSource(dataset); + populateFilters(dataset); + render(); + showToast( + `Se cargó "${file.name}": ${dataset.meta.courses} cursos, ${dataset.meta.records} evaluaciones.`, + ); + } catch (error) { + const details = Array.isArray(error.details) && error.details.length ? ` ${error.details.join(' ')}` : ''; + showToast(`No se pudo importar el archivo: ${error.message}${details}`, 7000); + } finally { + elements.fileInput.value = ''; + elements.fileInput.disabled = false; + elements.resetData.disabled = false; + } +} + +async function resetWorkbook() { + elements.resetData.disabled = true; + try { + const dataset = await requestJson('/api/reset', { method: 'POST' }); + state.dataset = dataset; + syncPeriodInput(dataset); + applyPeriodLabels(dataset); + elements.sourceSummary.textContent = describeSource(dataset); + populateFilters(dataset); + render(); + showToast('Se restauró el archivo de evaluaciones original.'); + } catch (error) { + showToast(`No se pudieron restaurar los datos: ${error.message}`, 6000); + } finally { + elements.resetData.disabled = false; + } +} + +/* -------------------------------------------------------------- view state */ + +function saveViewState() { + try { + window.localStorage.setItem( + VIEW_STATE_KEY, + JSON.stringify({ + filters: state.filters, + theme: state.theme, + period: state.periodTyped, + }), + ); + } catch { + // Private mode or storage disabled: filters simply will not be restored. + } +} + +function loadViewState() { + try { + const raw = window.localStorage.getItem(VIEW_STATE_KEY); + if (!raw) return; + const saved = JSON.parse(raw); + if (saved.filters && typeof saved.filters === 'object') { + state.filters = { ...state.filters, ...saved.filters }; + } + if (typeof saved.theme === 'string') state.theme = saved.theme; + if (typeof saved.period === 'string') { + state.periodTyped = saved.period; + } + } catch { + // Ignore malformed state. + } +} + +function syncFilterControls() { + elements.filterTerm.value = state.filters.term; + elements.filterSpecialty.value = state.filters.specialty; + elements.filterTeacher.value = state.filters.teacher; + elements.filterItem.value = state.filters.item; + elements.filterText.value = state.filters.text; +} + +function applyTheme() { + const root = document.documentElement; + if (state.theme === 'auto') root.removeAttribute('data-theme'); + else root.setAttribute('data-theme', state.theme); + elements.themeToggle.setAttribute( + 'aria-label', + `Cambiar tema de la interfaz (actual: ${themeLabel()})`, + ); +} + +function themeLabel() { + if (state.theme === 'auto') return 'automático'; + return state.theme === 'dark' ? 'oscuro' : 'claro'; +} + +/* ------------------------------------------------------------------ events */ + +elements.filterTerm.addEventListener('change', (event) => { + state.filters.term = event.target.value; + render(); + saveViewState(); +}); + +elements.filterSpecialty.addEventListener('change', (event) => { + state.filters.specialty = event.target.value; + render(); + saveViewState(); +}); + +elements.filterTeacher.addEventListener('change', (event) => { + state.filters.teacher = event.target.value; + render(); + saveViewState(); +}); + +elements.filterItem.addEventListener('change', (event) => { + state.filters.item = event.target.value; + render(); + saveViewState(); +}); + +let searchTimer = 0; +elements.filterText.addEventListener('input', (event) => { + state.filters.text = event.target.value; + window.clearTimeout(searchTimer); + searchTimer = window.setTimeout(() => { + render(); + saveViewState(); + }, 180); +}); + +elements.clearFilters.addEventListener('click', () => { + state.filters = { term: 'all', specialty: 'all', teacher: 'all', item: 'all', text: '' }; + syncFilterControls(); + render(); + saveViewState(); +}); + +elements.periodInput.addEventListener('input', () => { + state.periodTyped = elements.periodInput.value; + if (state.dataset) { + applyPeriodLabels(state.dataset); + elements.sourceSummary.textContent = describeSource(state.dataset); + render(); + } + saveViewState(); +}); + +elements.retryButton.addEventListener('click', () => { + loadDataset(); +}); + +elements.fileInput.addEventListener('change', (event) => { + const file = event.target.files?.[0]; + if (file) importWorkbook(file); +}); + +elements.resetData.addEventListener('click', () => { + resetWorkbook(); +}); + +elements.downloadTemplate.addEventListener('click', () => { + const period = String(state.dataset?.meta?.evaluationPeriod ?? 'periodo') + .replace(/[^\p{L}\p{N}._-]+/gu, '-') + .replace(/^-|-$/g, ''); + const link = document.createElement('a'); + link.href = '/api/template'; + link.download = `plantilla-evaluacion-${period || 'periodo'}.xlsx`; + document.body.appendChild(link); + link.click(); + link.remove(); +}); + +elements.themeToggle.addEventListener('click', () => { + state.theme = state.theme === 'auto' ? 'light' : state.theme === 'light' ? 'dark' : 'auto'; + applyTheme(); + saveViewState(); + if (state.dataset) render(); +}); + +elements.dialogClose.addEventListener('click', () => { + elements.dialog.close(); +}); + +elements.dialog.addEventListener('click', (event) => { + if (event.target === elements.dialog) elements.dialog.close(); +}); + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') saveViewState(); +}); + +/* -------------------------------------------------------------------- boot */ + +loadViewState(); +applyTheme(); +syncFilterControls(); +loadDataset(); diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/index.html b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/index.html new file mode 100644 index 00000000..4e038784 --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/index.html @@ -0,0 +1,244 @@ + + + + + + Sistema de análisis de la Evaluación Docente + + + + + + + + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ +
+ + Cargando evaluaciones… +
+ + +
+ + +
+
+

Detalle del curso

+

+
+ +
+
+
+ + + + + + diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/styles.css b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/styles.css new file mode 100644 index 00000000..2ede2b02 --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/client/styles.css @@ -0,0 +1,931 @@ +/* Sistema de análisis de la Evaluación Docente — Mini App client styles. + Palette and spacing follow the MiniMax Code Mini App visual baseline: semantic + --mcode-* variables, flat surfaces, 1px borders, restrained shadows. */ + +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; + + --chart-current: #0094fc; + --chart-historical: #b8b8b8; + --chart-grid: #0a0a0a12; + --chart-scale-low: #e7f4ff; + --chart-scale-high: #0a6fc4; + --chart-scale-text-on-dark: #ffffff; +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + + --chart-current: #3f9bfd; + --chart-historical: #5a5a5a; + --chart-grid: #ffffff14; + --chart-scale-low: #1d3d57; + --chart-scale-high: #7cc0ff; + --chart-scale-text-on-dark: #171717; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + + --chart-current: #3f9bfd; + --chart-historical: #5a5a5a; + --chart-grid: #ffffff14; + --chart-scale-low: #1d3d57; + --chart-scale-high: #7cc0ff; + --chart-scale-text-on-dark: #171717; + } +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; +} + +body { + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.55; + -webkit-font-smoothing: antialiased; +} + +h1, +h2, +h3 { + margin: 0; + font-weight: 600; + letter-spacing: -0.01em; +} + +h1 { + font-size: 18px; + line-height: 28px; +} + +h2 { + font-size: 16px; + line-height: 24px; +} + +p { + margin: 0; +} + +[hidden] { + display: none !important; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.skip-link { + position: absolute; + left: -9999px; + top: 0; + z-index: 20; + padding: 8px 12px; + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + border-radius: 8px; +} + +.skip-link:focus { + left: 16px; + top: 16px; +} + +:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 2px; +} + +/* ---------- header ---------- */ + +.page-header { + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: flex-start; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid var(--mcode-border); + background: var(--mcode-surface); +} + +.page-header__titles { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.page-header__subtitle { + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-muted); +} + +.period-field { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 6px; +} + +.period-field label { + font-size: 12px; + font-weight: 500; + color: var(--mcode-text-muted); +} + +.period-field__input { + width: 120px; + height: 30px; + padding: 0 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font: inherit; + font-size: 13px; +} + +.period-field__input:focus { + border-color: var(--mcode-accent); + outline: none; + box-shadow: 0 0 0 2px color-mix(in srgb, var(--mcode-accent) 25%, transparent); +} + +.period-field__input:disabled { + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + cursor: default; +} + +.period-field__hint { + font-size: 11px; + color: var(--mcode-text-subtle); +} + +.page-header__actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} + +/* ---------- buttons ---------- */ + +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 34px; + padding: 0 12px; + border: 1px solid transparent; + border-radius: 8px; + font: inherit; + font-size: 13px; + line-height: 1; + color: var(--mcode-text); + background: var(--mcode-surface-muted); + cursor: pointer; + transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out; + white-space: nowrap; +} + +.button--secondary { + border-color: var(--mcode-border); + background: var(--mcode-surface); +} + +.button--secondary:hover { + background: var(--mcode-surface-muted); + border-color: var(--mcode-border-strong); +} + +.button--icon { + width: 34px; + padding: 0; + border-color: var(--mcode-border); + background: var(--mcode-surface); +} + +.button--icon:hover { + background: var(--mcode-surface-muted); +} + +.button[disabled] { + opacity: 0.55; + cursor: not-allowed; +} + +label.button { + cursor: pointer; +} + +/* ---------- layout ---------- */ + +main { + max-width: 1280px; + margin: 0 auto; + padding: 24px; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: flex-end; + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.field { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 168px; +} + +.field--grow { + flex: 1 1 240px; +} + +.field label { + font-size: 12px; + font-weight: 500; + color: var(--mcode-text-muted); +} + +.field select, +.field input { + height: 36px; + padding: 0 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font: inherit; + font-size: 13px; +} + +.field select:focus, +.field input:focus { + border-color: var(--mcode-accent); + outline: none; + box-shadow: 0 0 0 2px color-mix(in srgb, var(--mcode-accent) 25%, transparent); +} + +.toolbar .button { + height: 36px; +} + +/* ---------- filter chips ---------- */ + +.chips { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 12px; + min-height: 24px; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + font-size: 12px; + color: var(--mcode-text); +} + +.chip button { + border: 0; + background: none; + padding: 0; + cursor: pointer; + color: var(--mcode-text-muted); + font: inherit; + line-height: 1; + display: inline-flex; +} + +.chip button:hover { + color: var(--mcode-danger); +} + +/* ---------- status ---------- */ + +.status-banner { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: space-between; + margin: 16px 24px 0; + padding: 12px 16px; + border-radius: 12px; + border: 1px solid var(--mcode-danger); + background: color-mix(in srgb, var(--mcode-danger) 8%, var(--mcode-surface)); + color: var(--mcode-text); + font-size: 13px; +} + +.loading { + display: flex; + align-items: center; + gap: 10px; + padding: 40px 0; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.loading__spinner { + width: 16px; + height: 16px; + border-radius: 50%; + border: 2px solid var(--mcode-border); + border-top-color: var(--mcode-accent); + animation: spin 700ms linear infinite; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: reduce) { + .loading__spinner { + animation: none; + } + + .button { + transition: none; + } +} + +/* ---------- KPIs ---------- */ + +.kpis { + display: grid; + grid-template-columns: 1.3fr 1fr 1fr 1fr; + gap: 16px; + margin-top: 24px; +} + +.kpi { + display: flex; + flex-direction: column; + gap: 6px; + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.kpi--primary { + background: var(--mcode-bg-secondary); +} + +.kpi__label { + font-size: 12px; + font-weight: 500; + color: var(--mcode-text-muted); +} + +.kpi__value { + font-size: 26px; + line-height: 32px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.kpi__detail { + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-muted); +} + +.kpi__value--up { + color: var(--mcode-success); +} + +.kpi__value--down { + color: var(--mcode-danger); +} + +/* ---------- panels ---------- */ + +.panel { + margin-top: 24px; + padding: 20px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.panel__header { + display: flex; + flex-direction: column; + gap: 4px; + margin-bottom: 16px; +} + +.panel__hint { + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-muted); +} + +.chart { + width: 100%; +} + +.chart svg { + display: block; + width: 100%; + height: auto; + overflow: visible; +} + +.chart--tall svg { + min-height: 260px; +} + +.chart__bar { + fill: var(--chart-current); +} + +.chart__bar--historical { + fill: var(--chart-historical); +} + +.chart__bar--interactive { + cursor: pointer; +} + +.chart__bar--interactive:hover { + fill: var(--mcode-accent); +} + +.chart__axis { + stroke: var(--mcode-border); + stroke-width: 1; +} + +.chart__grid { + stroke: var(--chart-grid); + stroke-width: 1; +} + +.chart__label { + fill: var(--mcode-text-muted); + font-size: 11px; +} + +.chart__value { + fill: var(--mcode-text); + font-size: 11px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.chart__meta { + fill: var(--mcode-text-muted); + font-size: 10px; + font-variant-numeric: tabular-nums; +} + +.chart__marker { + stroke: var(--mcode-text); + stroke-width: 1.5; +} + +.chart__legend { + display: flex; + flex-wrap: wrap; + gap: 16px; + margin-bottom: 12px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.chart__legend-item { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.chart__swatch { + width: 10px; + height: 10px; + border-radius: 2px; + background: var(--chart-current); +} + +.chart__swatch--historical { + background: var(--chart-historical); +} + +.chart__empty, +.empty-state { + padding: 28px 16px; + border: 1px dashed var(--mcode-border); + border-radius: 12px; + color: var(--mcode-text-muted); + font-size: 13px; + text-align: center; +} + +/* ---------- heatmap ---------- */ + +.table-scroll { + position: relative; + overflow-x: auto; + padding-bottom: 4px; +} + +.matrix { + border-collapse: separate; + border-spacing: 2px; + font-size: 11px; +} + +.matrix th { + font-weight: 500; + color: var(--mcode-text-muted); + text-align: left; + white-space: nowrap; + padding: 2px 6px; +} + +.matrix thead th { + text-align: center; + vertical-align: bottom; +} + +.matrix tbody th { + max-width: 240px; + overflow: hidden; + text-overflow: ellipsis; +} + +.matrix td { + min-width: 42px; + padding: 4px 6px; + text-align: center; + border-radius: 4px; + font-variant-numeric: tabular-nums; + cursor: pointer; +} + +.matrix td:hover { + outline: 2px solid var(--mcode-text); + outline-offset: -2px; +} + +.matrix__scale { + display: flex; + align-items: center; + gap: 8px; + margin-top: 12px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.matrix__scale-bar { + height: 10px; + flex: 0 0 160px; + border-radius: 999px; + background: linear-gradient( + to right, + var(--chart-scale-low), + var(--chart-scale-high) + ); +} + +/* ---------- comments ---------- */ + +.comments { + display: flex; + flex-direction: column; + gap: 12px; +} + +.comment { + padding: 12px 14px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface-muted); +} + +.comment__meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + margin-bottom: 6px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.comment__tag { + padding: 1px 8px; + border-radius: 999px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface); + font-size: 11px; +} + +.comment__text { + font-size: 13px; + line-height: 1.6; + white-space: pre-wrap; +} + +/* ---------- notes ---------- */ + +.notes { + display: flex; + flex-direction: column; + gap: 8px; + margin: 0; + padding: 0; + list-style: none; +} + +.note { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface-muted); + font-size: 13px; +} + +.note__badge { + flex: 0 0 auto; + padding: 1px 8px; + border-radius: 999px; + font-size: 11px; + font-weight: 500; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface); + color: var(--mcode-text-muted); +} + +.note--warning .note__badge { + border-color: var(--mcode-warning); + color: var(--mcode-warning); +} + +.method { + display: grid; + grid-template-columns: 200px 1fr; + gap: 8px 16px; + margin: 0; + font-size: 13px; +} + +.method dt { + color: var(--mcode-text-muted); +} + +.method dd { + margin: 0; +} + +/* ---------- dialog ---------- */ + +.detail { + width: min(880px, calc(100vw - 32px)); + max-height: min(80vh, 760px); + padding: 0; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + color: var(--mcode-text); + box-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +.detail::backdrop { + background: rgb(10 10 10 / 38%); +} + +.detail__header { + display: flex; + gap: 16px; + align-items: flex-start; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid var(--mcode-border); +} + +.detail__subtitle { + margin-top: 4px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.detail__body { + padding: 16px 20px 20px; + overflow-y: auto; + max-height: calc(min(80vh, 760px) - 74px); +} + +.detail__facts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin-bottom: 16px; +} + +.fact { + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface-muted); +} + +.fact__label { + font-size: 11px; + color: var(--mcode-text-muted); +} + +.fact__value { + margin-top: 2px; + font-size: 14px; + font-weight: 500; +} + +.detail table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.detail table th, +.detail table td { + padding: 8px 10px; + border-bottom: 1px solid var(--mcode-border); + text-align: left; + vertical-align: top; +} + +.detail table thead th { + font-size: 11px; + font-weight: 500; + color: var(--mcode-text-muted); + text-transform: none; +} + +.detail table td.numeric, +.detail table th.numeric { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.detail__section-title { + margin: 20px 0 8px; + font-size: 14px; +} + +.delta--up { + color: var(--mcode-success); +} + +.delta--down { + color: var(--mcode-danger); +} + +/* ---------- toast ---------- */ + +.toast { + position: fixed; + right: 24px; + bottom: 24px; + z-index: 30; + max-width: 420px; + padding: 12px 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + color: var(--mcode-text); + box-shadow: 0 0 20px rgb(10 10 10 / 8%); + font-size: 13px; +} + +/* ---------- responsive ---------- */ + +@media (max-width: 1080px) { + .kpis { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 768px) { + main { + padding: 16px; + } + + .page-header { + padding: 16px; + } + + .field { + min-width: 140px; + flex: 1 1 140px; + } + + .toolbar { + padding: 12px; + } + + .kpis { + grid-template-columns: 1fr; + gap: 12px; + } + + .panel { + padding: 16px; + } + + .method { + grid-template-columns: 1fr; + gap: 2px 0; + } + + .method dd { + margin-bottom: 8px; + } +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/miniapp.json b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/miniapp.json new file mode 100644 index 00000000..1f1f4be9 --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/miniapp.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard", + "window": { + "width": 1280, + "height": 900, + "minWidth": 480, + "minHeight": 360, + "resizable": true + } + }, + "mcpEndpoints": [] +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/data/estadistica.xlsx b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/data/estadistica.xlsx new file mode 100644 index 00000000..b6d3eacd Binary files /dev/null and b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/data/estadistica.xlsx differ diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/dataset.mjs b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/dataset.mjs new file mode 100644 index 00000000..b22b442f --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/dataset.mjs @@ -0,0 +1,783 @@ +/** + * Normalises an evaluation workbook into the fixed analysis contract used by the dashboard. + * + * The instrument is fixed by contract and is never inferred from the imported file: + * 10 source columns, 17 reactivos numbered 1..17, and one complete record per + * (curso, reactivo) pair. A workbook that does not honour that contract is rejected + * with an explicit message instead of being silently reshaped. + */ + +import { readWorkbook, WorkbookError } from './xlsx.mjs'; + +export const ITEM_COUNT = 17; +export const STATISTICS_SHEET = 'estadistica'; +export const ROSTER_SHEET = 'padron'; + +/** + * Required source columns and the spellings accepted for each of them. + * + * The column of the current period is deliberately absent: its label carries + * the period it measures ("Promedio 2026A", "Promedio 2026B", "Promedio + * 2027-1"…), so it is detected by shape instead of by an exact name. The + * instrument itself stays fixed: 17 reactivos, one row per curso y reactivo. + */ +export const SOURCE_COLUMNS = [ + { key: 'ID programa', aliases: ['id programa', 'idprograma', 'programa'] }, + { key: 'ID especialidad', aliases: ['id especialidad', 'idespecialidad', 'especialidad'] }, + { key: 'ID profesor', aliases: ['id profesor', 'idprofesor', 'profesor', 'docente'] }, + { key: 'Semestre', aliases: ['semestre', 'periodo', 'sem'] }, + { key: 'Reactivo', aliases: ['reactivo', 'reactivos', 'item', 'pregunta'] }, + { + key: 'Histórico', + aliases: ['historico', 'promedio historico', 'historico 2025', 'promedio historico 2025'], + patterns: [/^historico\b/, /^promedio\s+historico\b/], + }, + { key: 'Comentarios', aliases: ['comentarios', 'comentario', 'comentarios libres'] }, + { key: 'Participaron', aliases: ['participaron', 'participantes', 'respondieron'] }, + { key: 'Convocados', aliases: ['convocados', 'convocadas'] }, +]; + +/** Key used internally for the column that holds the average of the period. */ +const CURRENT_COLUMN = 'Promedio del período'; + +export class DatasetFormatError extends Error { + /** @param {string} message @param {string[]} [details] */ + constructor(message, details = []) { + super(message); + this.name = 'DatasetFormatError'; + this.details = details; + } +} + +/** + * @param {string} value + * @returns {string} + */ +function foldKey(value) { + return String(value ?? '') + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * @param {unknown} value + * @returns {string} + */ +function cleanText(value) { + if (value === null || value === undefined) return ''; + return String(value).replace(/\s+$/g, '').trim(); +} + +/** + * @param {unknown} value + * @returns {string} + */ +function cleanMultiline(value) { + if (value === null || value === undefined) return ''; + return String(value).replace(/[ \t]+\n/g, '\n').trim(); +} + +/** + * Split the free-text cell into individual student comments. + * @param {unknown} value + * @returns {string[]} + */ +export function splitComments(value) { + if (value === null || value === undefined) return []; + const text = String(value); + if (!text.trim()) return []; + return text + .split('|') + .map((part) => cleanMultiline(part.trim().replace(/^"|"$/g, '').trim())) + .filter((part) => part.length > 0); +} + +/** + * @param {unknown} value + * @param {string} label + * @returns {number} + */ +function requireNumber(value, label) { + if (value === null || value === undefined || value === '') { + throw new DatasetFormatError(`Falta el valor numérico de "${label}".`); + } + const numeric = typeof value === 'number' ? value : Number(String(value).replace(',', '.')); + if (!Number.isFinite(numeric)) { + throw new DatasetFormatError(`El valor de "${label}" no es numérico: "${String(value).slice(0, 40)}".`); + } + return numeric; +} + +/** + * Describe how a course's response count compares with the number of students summoned. + * @param {{ participants: number, convened: number, items: number }[]} variants + * @returns {'more' | 'less' | 'mixed' | null} + */ +function describeParticipationGap(variants) { + if (variants.length === 0) return null; + if (variants.length > 1) return 'mixed'; + const only = variants[0]; + if (only.participants === only.convened) return null; + return only.participants > only.convened ? 'more' : 'less'; +} + +/** + * @param {string} name + * @param {unknown} value + * @returns {string} + */ +function deriveSpecialty(name, value) { + const text = cleanText(value); + if (text) return text; + return name.replace(/^Maestría en\s+/i, '').trim() || name; +} + +/** + * Read a workbook and return the normalised dataset. + * @param {Buffer} buffer + * @returns {object} + */ +export function buildDataset(buffer) { + const { sheets } = readWorkbook(buffer); + const statisticsSheet = sheets.find((sheet) => foldKey(sheet.name) === STATISTICS_SHEET); + if (!statisticsSheet) { + throw new DatasetFormatError( + `El libro no contiene la hoja "${STATISTICS_SHEET}" con las evaluaciones.`, + [`Hojas encontradas: ${sheets.map((sheet) => sheet.name).join(', ')}`], + ); + } + const rosterSheet = sheets.find((sheet) => foldKey(sheet.name) === ROSTER_SHEET); + + const { header, rows } = readGrid(statisticsSheet.rows); + const columns = resolveColumns(header); + const columnIndex = columns.index; + + const roster = rosterSheet ? readRoster(rosterSheet.rows) : new Map(); + + /** @type {Map} */ + const itemText = new Map(); + /** @type {Map} */ + const byCourse = new Map(); + /** @type {Map} */ + const courseHeader = new Map(); + /** @type {any[]} */ + const allRecords = []; + let commentCount = 0; + let recordCount = 0; + + for (const row of rows) { + const courseId = cleanText(row[columnIndex['ID programa']]); + if (!courseId) continue; + const teacher = cleanText(row[columnIndex['ID profesor']]); + const term = cleanText(row[columnIndex['Semestre']]); + const rawItem = cleanText(row[columnIndex['Reactivo']]); + const itemMatch = /^(\d+)\s*(.*)$/.exec(rawItem); + if (!itemMatch) { + throw new DatasetFormatError(`El reactivo "${rawItem.slice(0, 60)}" no empieza con un número.`); + } + const item = Number.parseInt(itemMatch[1], 10); + const text = cleanMultiline(itemMatch[2]); + if (item < 1 || item > ITEM_COUNT) { + throw new DatasetFormatError( + `El reactivo ${item} está fuera del instrumento esperado (1..${ITEM_COUNT}).`, + ); + } + if (itemText.has(item) && itemText.get(item) !== text) { + throw new DatasetFormatError(`El reactivo ${item} tiene textos distintos entre cursos.`); + } + itemText.set(item, text); + + const historicalRaw = row[columnIndex['Histórico']]; + const historical = + historicalRaw === null || historicalRaw === undefined || historicalRaw === '' + ? null + : requireNumber(historicalRaw, 'Histórico'); + const current = requireNumber(row[columnIndex[CURRENT_COLUMN]], columns.currentLabel); + const participants = Math.round(requireNumber(row[columnIndex['Participaron']], 'Participaron')); + const convened = Math.round(requireNumber(row[columnIndex['Convocados']], 'Convocados')); + const comments = splitComments(row[columnIndex['Comentarios']]); + commentCount += comments.length; + + const percentRaw = + columns.participationPercentPosition === -1 + ? null + : row[columns.participationPercentPosition]; + const participationPercent = + percentRaw === null || percentRaw === undefined || percentRaw === '' + ? null + : requireNumber(percentRaw, columns.participationPercentLabel ?? 'Participación'); + + const record = { + course: courseId, + teacher, + term, + specialtyRaw: cleanText(row[columnIndex['ID especialidad']]), + item, + historical: historical === null ? null : Math.round(historical * 10000) / 10000, + current: Math.round(current * 10000) / 10000, + participants, + convened, + participationPercent, + comments, + }; + recordCount += 1; + allRecords.push(record); + if (!byCourse.has(courseId)) { + byCourse.set(courseId, []); + courseHeader.set(courseId, { teacher, term }); + } + byCourse.get(courseId).push(record); + } + + if (byCourse.size === 0) { + throw new DatasetFormatError('La hoja de evaluaciones no contiene registros.'); + } + if (itemText.size !== ITEM_COUNT) { + throw new DatasetFormatError( + `El instrumento debe tener ${ITEM_COUNT} reactivos y el archivo contiene ${itemText.size}.`, + ); + } + for (let item = 1; item <= ITEM_COUNT; item += 1) { + if (!itemText.has(item)) throw new DatasetFormatError(`Falta el reactivo ${item} en el archivo.`); + } + + const courses = []; + for (const [courseId, records] of byCourse) { + const items = new Set(records.map((record) => record.item)); + if (items.size !== ITEM_COUNT) { + throw new DatasetFormatError( + `El curso ${courseId} no tiene los ${ITEM_COUNT} reactivos (tiene ${items.size}).`, + ); + } + const teachers = [...new Set(records.map((record) => record.teacher))].filter(Boolean); + const rosterEntry = roster.get(courseId); + const { teacher, term } = courseHeader.get(courseId); + const specialtyRaw = cleanText(records[0].specialtyRaw); + + // A course can be split between several docentes, each one with their own + // group of students, so participation is counted per (curso, docente) and + // then summed for the course. + /** @type {Map, participationPercent: number | null }>} */ + const groupsByTeacher = new Map(); + for (const record of records) { + const key = record.teacher || ''; + let group = groupsByTeacher.get(key); + if (!group) { + group = { teacher: key, records: [], variants: new Map(), participationPercent: null }; + groupsByTeacher.set(key, group); + } + group.records.push(record); + const variantKey = `${record.participants}/${record.convened}`; + group.variants.set(variantKey, (group.variants.get(variantKey) ?? 0) + 1); + if (group.participationPercent === null && record.participationPercent !== null) { + group.participationPercent = record.participationPercent; + } + } + + const groups = [...groupsByTeacher.values()] + .map((group) => { + const variants = [...group.variants.entries()] + .map(([key, count]) => { + const [groupParticipants, groupConvened] = key.split('/').map(Number); + return { participants: groupParticipants, convened: groupConvened, items: count }; + }) + .sort((left, right) => right.items - left.items); + const first = group.records[0]; + const computed = first.convened > 0 ? (first.participants / first.convened) * 100 : null; + const declared = group.participationPercent; + return { + teacher: group.teacher, + teacherLabel: group.teacher || '(sin docente)', + participants: first.participants, + convened: first.convened, + items: group.records.length, + variants, + participationPercentComputed: computed === null ? null : Math.round(computed * 100) / 100, + participationPercentDeclared: declared, + participationPercent: + declared ?? (computed === null ? null : Math.round(computed * 100) / 100), + participationPercentSource: declared === null ? 'calculada' : 'declarada', + }; + }) + .sort((left, right) => left.teacherLabel.localeCompare(right.teacherLabel, 'es')); + + const participants = groups.reduce((total, group) => total + group.participants, 0); + const convened = groups.reduce((total, group) => total + group.convened, 0); + const declaredGroups = groups.filter((group) => group.participationPercentDeclared !== null); + const weighted = declaredGroups.reduce( + (total, group) => total + (group.participationPercent ?? 0) * group.convened, + 0, + ); + const weightedDenominator = groups.reduce( + (total, group) => total + (group.participationPercent !== null ? group.convened : 0), + 0, + ); + const participationPercent = + weightedDenominator > 0 + ? Math.round((weighted / weightedDenominator) * 100) / 100 + : convened > 0 + ? Math.round((participants / convened) * 10000) / 100 + : null; + + const variantCounts = new Map(); + for (const group of groups) { + for (const variant of group.variants) { + const key = `${variant.participants}/${variant.convened}`; + variantCounts.set(key, (variantCounts.get(key) ?? 0) + variant.items); + } + } + const participationVariants = [...variantCounts.entries()] + .map(([key, count]) => { + const [pairParticipants, pairConvened] = key.split('/').map(Number); + return { participants: pairParticipants, convened: pairConvened, items: count }; + }) + .sort((left, right) => right.items - left.items); + + const specialtySource = specialtyRaw || rosterEntry?.specialty || ''; + const program = rosterEntry?.program ?? ''; + courses.push({ + id: courseId, + teacher: teachers[0] ?? teacher ?? '', + teachers, + coTaught: teachers.length > 1, + subject: rosterEntry?.subject ?? '', + program, + specialty: deriveSpecialty(program, specialtySource), + specialtyFromSource: specialtyRaw, + term, + participants, + convened, + groups, + participationPercent, + participationVariants, + participationStable: participationVariants.length === 1, + participationGap: describeParticipationGap(participationVariants), + historicalAvailable: records.some((record) => record.historical !== null), + commentCount: records.reduce((total, record) => total + record.comments.length, 0), + }); + } + courses.sort((left, right) => left.id.localeCompare(right.id)); + + const items = Array.from({ length: ITEM_COUNT }, (_unused, index) => ({ + id: index + 1, + text: itemText.get(index + 1) ?? '', + })); + + const teachers = [ + ...new Set(allRecords.map((record) => record.teacher).filter(Boolean)), + ].sort((left, right) => left.localeCompare(right, 'es')); + + const notes = buildDataNotes(courses, allRecords, columns); + + return { + meta: { + sourceFile: 'Estadística.xlsx', + sourceSheets: sheets.map((sheet) => sheet.name), + evaluationPeriod: columns.currentPeriod, + historicalLabel: columns.historicalLabel, + currentLabel: columns.currentLabel, + participationPercentLabel: columns.participationPercentLabel, + extraColumns: columns.extraColumns, + records: recordCount, + courses: courses.length, + teachers: teachers.length, + items: items.length, + comments: commentCount, + rosterAvailable: Boolean(rosterSheet), + }, + items, + courses, + teachers, + records: allRecords, + notes, + }; +} + +/** + * @param {(string | number | null)[][]} grid + * @returns {{ header: string[], rows: (string | number | null)[][] }} + */ +function readGrid(grid) { + const headerIndex = grid.findIndex((row) => row.some((cell) => cleanText(cell) !== '')); + if (headerIndex === -1) throw new DatasetFormatError('La hoja de evaluaciones está vacía.'); + const header = grid[headerIndex].map((cell) => cleanText(cell)); + const rows = grid.slice(headerIndex + 1).filter((row) => row.some((cell) => cleanText(cell) !== '')); + return { header, rows }; +} + +/** + * Find the first column that matches an alias or a pattern. + * + * @param {string[]} folded + * @param {Set} used + * @param {string[]} aliases + * @param {RegExp[]} [patterns] + * @returns {number} + */ +function findColumn(folded, used, aliases, patterns = []) { + for (const alias of aliases) { + const position = folded.indexOf(foldKey(alias)); + if (position !== -1 && !used.has(position)) return position; + } + for (let position = 0; position < folded.length; position += 1) { + if (used.has(position)) continue; + if (patterns.some((pattern) => pattern.test(folded[position]))) return position; + } + return -1; +} + +/** + * Read the period carried by a header of the form "Promedio ". + * + * A header that names no period ("Promedio actual" or a bare "Promedio") is + * accepted too: that is what a template reused every semester needs. It + * returns an empty period in that case. + * + * @param {string} label + * @returns {string | null} the period, an empty string when the header names + * none, or null when the header is not an average column at all. + */ +function readPeriod(label) { + const match = /^promedio\s*(.*)$/i.exec(String(label ?? '').trim()); + if (!match) return null; + const rest = match[1].trim(); + const foldedRest = foldKey(rest); + if (rest === '' || foldedRest === 'actual' || foldedRest === 'current') return ''; + return rest; +} + +/** + * Distance between two strings, used to spot a header that is almost + * "Promedio" and to suggest the right spelling. + * + * @param {string} left + * @param {string} right + * @returns {number} + */ +function editDistance(left, right) { + const previous = Array.from({ length: right.length + 1 }, (_unused, index) => index); + for (let i = 0; i < left.length; i += 1) { + let diagonal = previous[0]; + previous[0] = i + 1; + for (let j = 0; j < right.length; j += 1) { + const above = previous[j + 1]; + const cost = left[i] === right[j] ? 0 : 1; + previous[j + 1] = Math.min(previous[j + 1] + 1, previous[j] + 1, diagonal + cost); + diagonal = above; + } + } + return previous[right.length]; +} + +/** + * Resolve the columns of the evaluation sheet. + * + * The file is allowed to differ from the bundled one: the period column is + * named after the period it measures, an optional column may declare the + * participation percentage per docente, and extra columns are ignored instead + * of rejected, so an edited template can be imported without reshaping it. + * + * @param {string[]} header + * @returns {{ index: Record, currentLabel: string, currentPeriod: string, historicalLabel: string, participationPercentLabel: string | null, participationPercentPosition: number, extraColumns: string[] }} + */ +function resolveColumns(header) { + const folded = header.map(foldKey); + const used = new Set(); + /** @type {Record} */ + const index = {}; + const missing = []; + + for (const column of SOURCE_COLUMNS) { + const position = findColumn(folded, used, column.aliases, column.patterns); + if (position === -1) missing.push(column.key); + else { + index[column.key] = position; + used.add(position); + } + } + + // The historical column can also be spelled "Promedio histórico"; it must be + // claimed before the current-period column is detected. + const historicalPosition = index['Histórico']; + const historicalLabel = historicalPosition === -1 ? 'Histórico' : header[historicalPosition]; + + const candidates = []; + for (let position = 0; position < header.length; position += 1) { + if (used.has(position)) continue; + const period = readPeriod(header[position]); + if (period === null) continue; + candidates.push({ position, label: header[position], period }); + } + + const found = header.filter((cell) => cell !== '').join(' | '); + const problems = []; + if (missing.length > 0) problems.push(`Columnas faltantes: ${missing.join(', ')}.`); + + // "Promedio actual" and a specific "Promedio " can coexist: the + // specific one wins. + const specific = candidates.filter((candidate) => candidate.period !== ''); + /** @type {{ position: number, label: string, period: string } | null} */ + let selected = null; + if (candidates.length === 1) selected = candidates[0]; + else if (specific.length === 1) selected = specific[0]; + + if (candidates.length === 0) { + problems.push( + 'No se encontró la columna del promedio del período (se espera un encabezado como "Promedio 2027A" o "Promedio actual").', + ); + const nearMiss = header + .filter((_label, position) => !used.has(position)) + .map((label) => ({ label, distance: editDistance(foldKey(label).split(' ')[0], 'promedio') })) + .filter((entry) => entry.distance > 0 && entry.distance <= 2) + .sort((left, right) => left.distance - right.distance); + if (nearMiss.length > 0) { + problems.push( + `El encabezado "${nearMiss[0].label}" parece un error de escritura: renómbralo a "Promedio " (por ejemplo "Promedio 2027A") o a "Promedio actual".`, + ); + } + } else if (selected === null) { + problems.push( + `Hay varias columnas de promedio (${candidates + .map((candidate) => candidate.label) + .join(', ')}) y no se sabe cuál es la del período. Deja en el archivo solo la que quieras analizar.`, + ); + } + if (problems.length > 0) { + problems.push(`Encabezados encontrados: ${found || '(ninguno)'}.`); + throw new DatasetFormatError( + 'El archivo no cumple el formato de evaluaciones esperado.', + problems, + ); + } + + const current = selected; + index[CURRENT_COLUMN] = current.position; + used.add(current.position); + for (const candidate of candidates) used.add(candidate.position); + + // Optional column with the participation percentage declared by the user. + let participationPercentPosition = -1; + for (let position = 0; position < header.length; position += 1) { + if (used.has(position)) continue; + const name = folded[position]; + if (name.includes('participacion') || (name.includes('porcentaje') && name.includes('particip'))) { + participationPercentPosition = position; + break; + } + } + if (participationPercentPosition !== -1) used.add(participationPercentPosition); + + const extraColumns = []; + for (let position = 0; position < header.length; position += 1) { + if (!used.has(position) && header[position]) extraColumns.push(header[position]); + } + + return { + index, + currentLabel: current.label, + currentPeriod: current.period, + historicalLabel, + participationPercentLabel: + participationPercentPosition === -1 ? null : header[participationPercentPosition], + participationPercentPosition, + extraColumns, + }; +} + +/** + * @param {(string | number | null)[][]} grid + * @returns {Map} + */ +function readRoster(grid) { + const { header, rows } = readGrid(grid); + const folded = header.map(foldKey); + const pick = (name) => { + const position = folded.indexOf(foldKey(name)); + return position === -1 ? -1 : position; + }; + const idColumn = pick('ID'); + const nameColumn = pick('Nombre'); + const subjectColumn = pick('Materia'); + const programColumn = pick('Programa'); + const specialtyColumn = pick('Especialidad'); + + /** @type {Map} */ + const roster = new Map(); + for (const row of rows) { + const id = cleanText(idColumn === -1 ? row[0] : row[idColumn]); + if (!id) continue; + roster.set(id, { + subject: subjectColumn === -1 ? '' : cleanText(row[subjectColumn]), + program: programColumn === -1 ? '' : cleanText(row[programColumn]), + specialty: specialtyColumn === -1 ? '' : cleanText(row[specialtyColumn]), + }); + } + return roster; +} + +/** + * Describe the anomalies actually present in the data. + * @param {any[]} courses + * @param {any[]} records + * @param {{ participationPercentLabel: string | null, extraColumns: string[] }} columns + * @returns {{ id: string, tone: string, text: string }[]} + */ +function buildDataNotes(courses, records, columns) { + const notes = []; + + const more = courses.filter((course) => course.participationGap === 'more'); + const less = courses.filter((course) => course.participationGap === 'less'); + const mixed = courses.filter((course) => course.participationGap === 'mixed'); + if (more.length > 0) { + notes.push({ + id: 'participacion-mayor', + tone: 'warning', + text: `${more.length} ${more.length === 1 ? 'curso reporta' : 'cursos reportan'} más respuestas que estudiantes convocados (${more + .map((course) => `${course.id}: ${course.participants}/${course.convened}`) + .join(', ')}).`, + }); + } + if (less.length > 0) { + notes.push({ + id: 'participacion-menor', + tone: 'warning', + text: `${less.length} ${less.length === 1 ? 'curso no alcanza' : 'cursos no alcanzan'} la totalidad de los convocados (${less + .map((course) => `${course.id}: ${course.participants}/${course.convened}`) + .join(', ')}).`, + }); + } + if (mixed.length > 0) { + notes.push({ + id: 'participacion-mixta', + tone: 'warning', + text: `${mixed.length} ${mixed.length === 1 ? 'curso combina' : 'cursos combinan'} grupos de respuesta distintos entre reactivos (${mixed + .map( + (course) => + `${course.id}: ${course.participationVariants + .map((variant) => `${variant.participants}/${variant.convened} en ${variant.items} reactivos`) + .join(' y ')}`, + ) + .join('; ')}).`, + }); + } + + const withoutHistory = courses.filter((course) => !course.historicalAvailable); + if (withoutHistory.length > 0) { + notes.push({ + id: 'sin-historico', + tone: 'neutral', + text: `${withoutHistory.length} de ${courses.length} cursos no tienen línea base histórica (${withoutHistory + .map((course) => course.id) + .join(', ')}); la comparación contra el histórico se calcula solo sobre los que sí la tienen.`, + }); + } + + const coTaught = courses.filter((course) => course.coTaught); + if (coTaught.length > 0) { + notes.push({ + id: 'codocencia', + tone: 'neutral', + text: `${coTaught.length} ${coTaught.length === 1 ? 'curso es impartido' : 'cursos son impartidos'} por más de un docente (${coTaught + .map((course) => `${course.id}: ${course.teachers.join(' + ')}`) + .join('; ')}).`, + }); + } + + const splitCourses = courses.filter((course) => course.groups.length > 1); + if (splitCourses.length > 0) { + notes.push({ + id: 'clases-divididas', + tone: 'neutral', + text: `${splitCourses.length} ${splitCourses.length === 1 ? 'curso se divide' : 'cursos se dividen'} entre varios docentes con grupos de alumnos distintos (${splitCourses + .map( + (course) => + `${course.id}: ${course.groups + .map( + (group) => + `${group.teacherLabel} ${group.participants}/${group.convened}${ + group.participationPercent !== null ? ` (${group.participationPercent} %)` : '' + }`, + ) + .join(' + ')}`, + ) + .join('; ')}); la participación se cuenta por grupo de docente.`, + }); + } + + if (columns.participationPercentLabel) { + const declared = courses + .flatMap((course) => course.groups) + .filter((group) => group.participationPercentDeclared !== null); + const mismatched = declared.filter( + (group) => + group.participationPercentComputed !== null && + Math.abs(group.participationPercentDeclared - group.participationPercentComputed) > 0.5, + ); + notes.push({ + id: 'participacion-declarada', + tone: mismatched.length > 0 ? 'warning' : 'neutral', + text: + `La columna "${columns.participationPercentLabel}" declara la participación por docente y se usa en lugar de la calculada en ${declared.length} ${declared.length === 1 ? 'grupo' : 'grupos'}` + + (mismatched.length > 0 + ? `; ${mismatched.length} difieren de la calculada (${mismatched + .map( + (group) => + `${group.teacherLabel}: ${group.participationPercentDeclared} % frente a ${group.participationPercentComputed} %`, + ) + .join('; ')}).` + : '.'), + }); + } + + if (columns.extraColumns.length > 0) { + notes.push({ + id: 'columnas-extra', + tone: 'neutral', + text: `El archivo trae ${columns.extraColumns.length} ${columns.extraColumns.length === 1 ? 'columna que el tablero no usa' : 'columnas que el tablero no usa'} (${columns.extraColumns.join(', ')}); se ignoran sin alterar los cálculos.`, + }); + } + + const teachersWithSeveral = []; + const byTeacher = new Map(); + for (const course of courses) { + const list = byTeacher.get(course.teacher) ?? []; + list.push(course.id); + byTeacher.set(course.teacher, list); + } + for (const [teacher, list] of byTeacher) { + if (list.length > 1) teachersWithSeveral.push(`${teacher} (${list.join(', ')})`); + } + if (teachersWithSeveral.length > 0) { + notes.push({ + id: 'docentes-multiples', + tone: 'neutral', + text: `${teachersWithSeveral.length} docentes imparten más de un curso en el periodo: ${teachersWithSeveral.join('; ')}.`, + }); + } + + const commentItems = new Set(); + for (const record of records) { + if (record.comments.length > 0) commentItems.add(record.item); + } + if (commentItems.size > 0) { + const list = [...commentItems].sort((left, right) => left - right); + notes.push({ + id: 'comentarios-reactivo', + tone: 'neutral', + text: + list.length === 1 + ? `Los comentarios libres se registran en el reactivo ${list[0]} de la hoja de origen.` + : `Los comentarios libres se registran en los reactivos ${list.join(', ')} de la hoja de origen.`, + }); + } + + if (notes.length === 0) { + notes.push({ id: 'sin-anomalias', tone: 'neutral', text: 'No se detectaron anomalías de participación ni huecos en el histórico.' }); + } + return notes; +} + +export { WorkbookError }; diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/miniapp-api.ts b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..1b68a48d --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/miniapp-api.ts @@ -0,0 +1,686 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The manifest did not declare the required grant; not dispatched. */ + | 'NOT_PERMITTED' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'PERMISSION_DENIED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Always present. Without `permissions.tool: ["call"]` (or the older `"toolAccess": ["call"]`), + * every method rejects `NOT_PERMITTED`. With `tool:call` switched off, `call()` rejects + * `PERMISSION_DENIED` while `list()` and `request()` resolve with `deny` for each tool. Every `call` + * is judged by the user's global rules: `deny` is `PERMISSION_DENIED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Always present. `run` / `reply` / `answer` / `models` / `list` / `create` need + * `permissions.agent: ["run"]`. The deprecated `observe` / `sessions` / `session` are the + * `context.session` methods and follow its rule (see agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `list()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `list` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `list()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** @deprecated Use `context.session.observe`; the Host warns once and removes this name in a later version. */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** @deprecated Use `context.session.list`; the Host warns once and removes this name in a later version. */ + sessions(): Promise; + /** @deprecated Use `context.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise; +} + +/** + * Always present. Read-only access to the user's conversations (the Desktop chat list). + * Every method needs `permissions.session: ["read"]`, except that this Mini App's own sessions (those + * `agent.create` / `agent.run` made) are readable under `permissions.agent: ["run"]` alone; while the + * user has `read` switched off, calls on other sessions fail with `PERMISSION_DENIED` and running + * observers end. Check `context.capabilities?.has('session.list')` on Hosts that may predate it. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionClient { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session.get()`). + */ + get(sessionId: string): Promise; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of the methods this Host offers **on the Node side**, named by API path + * (`agent.run`, `agent.list`, `session.list`, `session.get`, `session.observe`, + * `connector.call`, `connector.list`, `tool.call`, `tool.list`, `tool.request`). A + * page-only method is false here. A few Host-wide names remain until the deprecated aliases go: + * `agent.agents`, `agent.observe`, `agent.sessions`, `agent.session`, `hostConnector`, `tool`. + * The `hostConnector*` probe names stay beside `connector.*` until the alias goes. + * It says nothing about this Mini App's manifest or authorization: `has('agent.run')` is true + * even when the manifest does not grant it. Older Hosts do not + * inject `capabilities`; check `context.capabilities?.has(...)`. `has('session.list')` tells a + * `context.session` Host from one that only has the deprecated `context.agent.sessions` names. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Always present. Without `permissions.connector` (or the older `hostConnectorAccess`), every + * method rejects `NOT_PERMITTED`. A provider the user switched off is missing from `list()` + * and its calls reject with `PERMISSION_DENIED`. + */ + readonly connector: HostConnectorClient; + /** + * @deprecated `connector`. Always present. Forwards to the same client and warns once on the first method call + * (`MINIAPP-DEP-007`); it is not the same object reference, so do not compare the two or use + * both as map keys. + */ + readonly hostConnector: HostConnectorClient; + /** Always present. Calls installed MCP and Connector tools under the user's permission rules. */ + readonly tool: MiniAppToolClient; + /** + * Always present, as on the page. Its methods need `permissions.agent: ["run"]`; they reject + * with `NOT_PERMITTED` if the manifest does not declare it and `PERMISSION_DENIED` if the user + * switched it off. Session aliases follow `context.session`'s rules. + */ + readonly agent: MiniAppAgentClient; + /** + * Always present, as on the page. Reading conversations other than this Mini App's own needs + * `permissions.session: ["read"]`. Own sessions can also use `permissions.agent: ["run"]`. + */ + readonly session: MiniAppSessionClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/server.mjs b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/server.mjs new file mode 100644 index 00000000..f2b2451a --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/server.mjs @@ -0,0 +1,250 @@ +// @ts-check + +import { readFile, writeFile, rename, mkdir, unlink } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; + +import { buildDataset, DatasetFormatError } from './dataset.mjs'; +import { WorkbookError } from './xlsx.mjs'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const CLIENT_DIR = 'miniapp/client'; +const SOURCE_WORKBOOK = 'miniapp/node/data/estadistica.xlsx'; +const IMPORTED_WORKBOOK = 'imported-source.xlsx'; +const MAX_UPLOAD_BYTES = 25 * 1024 * 1024; + +const CONTENT_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', +}; + +/** + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + const sourcePath = join(context.pluginRoot, SOURCE_WORKBOOK); + const importedPath = join(context.dataDir, IMPORTED_WORKBOOK); + + /** @type {object | null} */ + let dataset = null; + /** @type {string} */ + let sourceLabel = 'Estadística.xlsx'; + /** @type {Buffer | null} */ + let sourceBuffer = null; + /** @type {Promise | null} */ + let pending = null; + + /** Load the dataset once; a persisted import wins over the bundled workbook. */ + const loadDataset = () => { + if (dataset) return Promise.resolve(dataset); + if (!pending) { + pending = (async () => { + let buffer = null; + try { + buffer = await readFile(importedPath); + sourceLabel = 'archivo importado'; + } catch { + buffer = await readFile(sourcePath); + sourceLabel = 'Estadística.xlsx'; + } + sourceBuffer = buffer; + const built = buildDataset(buffer); + dataset = { ...built, meta: { ...built.meta, sourceLabel } }; + return dataset; + })().catch((error) => { + pending = null; + throw error; + }); + } + return pending; + }; + + const server = createServer((request, response) => { + handle(request, response).catch((error) => { + context.logger.error('miniapp.request.failed', { message: String(error?.message ?? error) }); + if (!response.headersSent) { + response.writeHead(500, { 'content-type': 'application/json; charset=utf-8' }); + } + response.end(JSON.stringify({ error: 'server_error', message: 'No se pudo completar la solicitud.' })); + }); + }); + + /** + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + */ + async function handle(request, response) { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const method = request.method ?? 'GET'; + + if (method === 'GET' && url.pathname === '/api/dataset') { + const built = await loadDataset(); + const body = JSON.stringify(built); + response.writeHead(200, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }); + response.end(body); + return; + } + + if (method === 'POST' && url.pathname === '/api/import') { + const buffer = await readBody(request); + let built; + try { + built = buildDataset(buffer); + } catch (error) { + const status = error instanceof DatasetFormatError || error instanceof WorkbookError ? 400 : 500; + response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' }); + response.end( + JSON.stringify({ + error: status === 400 ? 'invalid_workbook' : 'server_error', + message: + status === 400 + ? String(error?.message ?? 'El archivo no pudo procesarse.') + : 'No se pudo procesar el archivo.', + details: error instanceof DatasetFormatError ? error.details : [], + }), + ); + return; + } + await mkdir(context.dataDir, { recursive: true }); + await writeFileAtomically(importedPath, buffer); + sourceBuffer = buffer; + dataset = { ...built, meta: { ...built.meta, sourceLabel: 'archivo importado' } }; + sourceLabel = 'archivo importado'; + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify(dataset)); + return; + } + + if (method === 'GET' && url.pathname === '/api/template') { + // The workbook in use, so it can be edited in a spreadsheet and imported back. + const current = dataset ?? (await loadDataset()); + const buffer = sourceBuffer ?? (await readFile(sourcePath)); + const period = String(current?.meta?.evaluationPeriod ?? 'periodo') + .replace(/[^\p{L}\p{N}._-]+/gu, '-') + .replace(/^-|-$/g, ''); + const fileName = `plantilla-evaluacion-${period || 'periodo'}.xlsx`; + response.writeHead(200, { + 'content-type': + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'content-disposition': `attachment; filename="${fileName}"`, + 'content-length': String(buffer.length), + 'cache-control': 'no-store', + }); + response.end(buffer); + return; + } + + if (method === 'POST' && url.pathname === '/api/reset') { + try { + await unlink(importedPath); + } catch { + // Nothing persisted yet: the bundled workbook is already in use. + } + dataset = null; + pending = null; + const built = await loadDataset(); + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify(built)); + return; + } + + if (method === 'GET' && (url.pathname === '/dashboard' || url.pathname === '/')) { + const html = await readFile(join(context.pluginRoot, CLIENT_DIR, 'index.html')); + response.writeHead(200, { 'content-type': CONTENT_TYPES['.html'] }); + response.end(html); + return; + } + + if (method === 'GET' && url.pathname.startsWith('/assets/')) { + const name = url.pathname.slice('/assets/'.length); + if (!/^[a-z0-9._-]+$/i.test(name)) { + response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'not_found' })); + return; + } + const extension = name.slice(name.lastIndexOf('.')).toLowerCase(); + const contentType = CONTENT_TYPES[extension]; + if (!contentType) { + response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'not_found' })); + return; + } + const asset = await readFile(join(context.pluginRoot, CLIENT_DIR, name)); + response.writeHead(200, { 'content-type': contentType, 'cache-control': 'no-store' }); + response.end(asset); + return; + } + + response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'not_found' })); + } + + await new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(undefined); + }); + }); + context.logger.info('miniapp.runtime.listening'); + + let disposal; + const dispose = () => { + if (disposal) return disposal; + context.signal.removeEventListener('abort', onAbort); + disposal = new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve(undefined)); + }); + return disposal; + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise} + */ +function readBody(request) { + return new Promise((resolve, reject) => { + /** @type {Buffer[]} */ + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_UPLOAD_BYTES) { + reject(new Error('El archivo excede el tamaño máximo permitido (25 MB).')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks))); + request.on('error', (error) => reject(error)); + }); +} + +/** + * Write a file atomically: a temporary file in the same directory, then a rename. + * @param {string} target + * @param {Buffer} content + */ +async function writeFileAtomically(target, content) { + const temporary = `${target}.tmp`; + await writeFile(temporary, content); + await rename(temporary, target); +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/xlsx.mjs b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/xlsx.mjs new file mode 100644 index 00000000..040d71a6 --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/miniapp/node/xlsx.mjs @@ -0,0 +1,310 @@ +/** + * Minimal, dependency-free reader for SpreadsheetML (.xlsx) workbooks. + * + * Scope: the OOXML subset Excel writes for a plain grid workbook — a ZIP container + * holding `xl/workbook.xml`, `xl/_rels/workbook.xml.rels`, `xl/sharedStrings.xml` + * and one `xl/worksheets/sheetN.xml` per sheet. Inline strings, shared strings, + * formula results and plain numbers are supported; styles, dates and drawings are + * not interpreted. + */ + +import { inflateRawSync } from 'node:zlib'; + +const EOCD_SIGNATURE = 0x06054b50; +const CENTRAL_SIGNATURE = 0x02014b50; +const LOCAL_SIGNATURE = 0x04034b50; + +/** + * XML patterns, declared once at module scope. Keeping every pattern out of the + * function bodies avoids the parser ambiguity that a `/…\/…/` literal can create + * inside a nested block. Only the single-match pattern is shared directly; the + * looping ones are copied per use so their `lastIndex` never leaks between calls. + */ +const SHARED_STRING_ITEM = /]*?(?:\/>|>([\s\S]*?)<\/si>)/g; +const TEXT_NODE = /]*>([\s\S]*?)<\/t>/g; +const CELL = /]*?)(?:\/>|>([\s\S]*?)<\/c>)/g; +const VALUE_CELL = /]*>([\s\S]*?)<\/v>/; + +/** + * @param {RegExp} pattern + * @returns {RegExp} + */ +function globalCopy(pattern) { + return new RegExp(pattern.source, 'g'); +} + +export class WorkbookError extends Error { + /** @param {string} code @param {string} message */ + constructor(code, message) { + super(message); + this.name = 'WorkbookError'; + this.code = code; + } +} + +/** + * Read every member of a ZIP archive into memory. + * @param {Buffer} buffer + * @returns {Map} + */ +export function readZipEntries(buffer) { + if (!Buffer.isBuffer(buffer) || buffer.length < 22) { + throw new WorkbookError('NOT_A_ZIP', 'El archivo está vacío o no es un libro de Excel válido.'); + } + const eocd = findEndOfCentralDirectory(buffer); + const entryCount = buffer.readUInt16LE(eocd + 10); + let offset = buffer.readUInt32LE(eocd + 16); + /** @type {Map} */ + const entries = new Map(); + + for (let index = 0; index < entryCount; index += 1) { + if (offset + 46 > buffer.length || buffer.readUInt32LE(offset) !== CENTRAL_SIGNATURE) break; + const method = buffer.readUInt16LE(offset + 10); + let compressedSize = buffer.readUInt32LE(offset + 20); + const nameLength = buffer.readUInt16LE(offset + 28); + const extraLength = buffer.readUInt16LE(offset + 30); + const commentLength = buffer.readUInt16LE(offset + 32); + const localOffset = buffer.readUInt32LE(offset + 42); + const name = buffer.toString('utf8', offset + 46, offset + 46 + nameLength); + + if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== LOCAL_SIGNATURE) { + throw new WorkbookError('CORRUPT_ZIP', `El archivo comprimido está dañado (entrada "${name}").`); + } + const localNameLength = buffer.readUInt16LE(localOffset + 26); + const localExtraLength = buffer.readUInt16LE(localOffset + 28); + const dataStart = localOffset + 30 + localNameLength + localExtraLength; + if (compressedSize === 0) compressedSize = buffer.readUInt32LE(localOffset + 18); + const raw = buffer.subarray(dataStart, dataStart + compressedSize); + + let content; + if (method === 0) { + content = Buffer.from(raw); + } else if (method === 8) { + try { + content = inflateRawSync(raw); + } catch { + throw new WorkbookError('CORRUPT_ZIP', `No se pudo descomprimir la entrada "${name}".`); + } + } else { + throw new WorkbookError('UNSUPPORTED_ZIP', `El archivo usa un método de compresión no soportado (${method}).`); + } + entries.set(name, content); + offset += 46 + nameLength + extraLength + commentLength; + } + return entries; +} + +/** + * @param {Buffer} buffer + * @returns {number} + */ +function findEndOfCentralDirectory(buffer) { + const minimum = Math.max(0, buffer.length - 65557); + for (let index = buffer.length - 22; index >= minimum; index -= 1) { + if (buffer.readUInt32LE(index) === EOCD_SIGNATURE) return index; + } + throw new WorkbookError('NOT_A_ZIP', 'El archivo no es un libro de Excel válido (no es un contenedor ZIP).'); +} + +/** + * @param {string} xml + * @returns {string} + */ +function decodeXmlText(xml) { + if (!xml.includes('&')) return xml; + return xml + .replace(/&#x([0-9a-fA-F]+);/g, (_match, hex) => String.fromCodePoint(Number.parseInt(hex, 16))) + .replace(/&#(\d+);/g, (_match, digits) => String.fromCodePoint(Number.parseInt(digits, 10))) + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&'); +} + +/** + * @param {string} tag + * @param {string} name + * @returns {string | null} + */ +function readAttribute(tag, name) { + const match = new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`).exec(tag); + return match ? decodeXmlText(match[1]) : null; +} + +/** + * @param {string} xml + * @returns {string[]} + */ +function parseSharedStrings(xml) { + /** @type {string[]} */ + const strings = []; + const pattern = globalCopy(SHARED_STRING_ITEM); + let match; + while ((match = pattern.exec(xml)) !== null) { + const inner = match[1] ?? ''; + let text = ''; + const textPattern = globalCopy(TEXT_NODE); + let textMatch; + while ((textMatch = textPattern.exec(inner)) !== null) { + text += decodeXmlText(textMatch[1]); + } + strings.push(text); + } + return strings; +} + +/** + * @param {string} reference e.g. "AB12" + * @returns {{ row: number, column: number }} + */ +function parseCellReference(reference) { + const match = /^([A-Z]+)(\d+)$/.exec(reference.toUpperCase()); + if (!match) return { row: 0, column: 0 }; + let column = 0; + for (const letter of match[1]) column = column * 26 + (letter.charCodeAt(0) - 64); + return { row: Number.parseInt(match[2], 10), column: column - 1 }; +} + +/** + * Parse one worksheet into a dense array of rows. + * @param {string} xml + * @param {string[]} sharedStrings + * @returns {(string | number | null)[][]} + */ +function parseSheet(xml, sharedStrings) { + /** @type {Map>} */ + const cells = new Map(); + const pattern = globalCopy(CELL); + let match; + + while ((match = pattern.exec(xml)) !== null) { + const attributes = match[1] ?? ''; + const inner = match[2] ?? ''; + const reference = readAttribute(attributes, 'r'); + const type = readAttribute(attributes, 't'); + const position = reference ? parseCellReference(reference) : null; + const row = position ? position.row : 0; + const column = position ? position.column : 0; + + let value = null; + if (type === 'inlineStr') { + value = extractText(inner); + } else { + const valueMatch = VALUE_CELL.exec(inner); + const raw = valueMatch ? decodeXmlText(valueMatch[1]) : ''; + if (type === 's') { + const index = Number.parseInt(raw, 10); + value = Number.isFinite(index) ? (sharedStrings[index] ?? '') : ''; + } else if (type === 'b') { + value = raw === '1' ? 'TRUE' : 'FALSE'; + } else if (type === 'str' || type === 'e') { + value = raw; + } else if (raw === '') { + value = null; + } else { + const numeric = Number(raw); + value = Number.isFinite(numeric) ? numeric : raw; + } + } + + if (!cells.has(row)) cells.set(row, new Map()); + cells.get(row).set(column, value); + } + + const maxRow = cells.size ? Math.max(...cells.keys()) : 0; + /** @type {(string | number | null)[][]} */ + const rows = []; + for (let row = 1; row <= maxRow; row += 1) { + const rowCells = cells.get(row); + if (!rowCells) { + rows.push([]); + continue; + } + const maxColumn = Math.max(...rowCells.keys()); + const line = []; + for (let column = 0; column <= maxColumn; column += 1) { + line.push(rowCells.has(column) ? rowCells.get(column) : null); + } + rows.push(line); + } + return rows; +} + +/** + * @param {string} inner + * @returns {string} + */ +function extractText(inner) { + let text = ''; + const pattern = globalCopy(TEXT_NODE); + let match; + while ((match = pattern.exec(inner)) !== null) text += decodeXmlText(match[1]); + return text; +} + +/** + * Read a workbook and return each sheet as a dense array of rows. + * @param {Buffer} buffer + * @returns {{ sheets: Array<{ name: string, rows: (string | number | null)[][] }> }} + */ +export function readWorkbook(buffer) { + const entries = readZipEntries(buffer); + const workbookPath = 'xl/workbook.xml'; + const workbookXml = entries.get(workbookPath); + if (!workbookXml) { + throw new WorkbookError('NOT_A_WORKBOOK', 'El archivo no contiene un libro de Excel válido.'); + } + const workbookText = workbookXml.toString('utf8'); + + const relsPath = 'xl/_rels/workbook.xml.rels'; + const relsXml = entries.get(relsPath); + /** @type {Map} */ + const relationships = new Map(); + if (relsXml) { + const relsText = relsXml.toString('utf8'); + const relPattern = /]*?)\/>/g; + let relMatch; + while ((relMatch = relPattern.exec(relsText)) !== null) { + const id = readAttribute(relMatch[1] ?? '', 'Id'); + const target = readAttribute(relMatch[1] ?? '', 'Target'); + if (id && target) relationships.set(id, target); + } + } + + const sharedStringsXml = entries.get('xl/sharedStrings.xml'); + const sharedStrings = sharedStringsXml ? parseSharedStrings(sharedStringsXml.toString('utf8')) : []; + + /** @type {Array<{ name: string, rows: (string | number | null)[][] }>} */ + const sheets = []; + const sheetPattern = /]*?)\/>/g; + let sheetMatch; + let fallbackIndex = 0; + while ((sheetMatch = sheetPattern.exec(workbookText)) !== null) { + const attributes = sheetMatch[1] ?? ''; + const name = readAttribute(attributes, 'name') ?? `Hoja${fallbackIndex + 1}`; + const relationId = readAttribute(attributes, 'r:id') ?? readAttribute(attributes, 'id'); + fallbackIndex += 1; + + const target = relationId ? relationships.get(relationId) : undefined; + const resolved = resolveWorkbookPath(target ?? `worksheets/sheet${fallbackIndex}.xml`); + const sheetXml = entries.get(resolved); + if (!sheetXml) continue; + sheets.push({ name, rows: parseSheet(sheetXml.toString('utf8'), sharedStrings) }); + } + + if (sheets.length === 0) { + throw new WorkbookError('NO_SHEETS', 'El libro no contiene hojas de cálculo legibles.'); + } + return { sheets }; +} + +/** + * @param {string} target + * @returns {string} + */ +function resolveWorkbookPath(target) { + let path = target.replace(/^\//, ''); + if (!path.startsWith('xl/')) path = `xl/${path.replace(/^\.\//, '')}`; + return path; +} diff --git a/plugins/salvadorfernandezm/teacher-evaluation-dashboard/package.json b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/salvadorfernandezm/teacher-evaluation-dashboard/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}