283 lines
12 KiB
JavaScript
283 lines
12 KiB
JavaScript
/**
|
|
* js/app.js
|
|
* Controlador principal de la UI. Lee desde api.js y actualiza el DOM + charts.js
|
|
*/
|
|
|
|
import { api } from './api.js';
|
|
import { chartsManager } from './charts.js';
|
|
|
|
// utils
|
|
function shortName(name) { const p = name.split(' '); return p[0] + (p[1] ? ' ' + p[1] : ''); }
|
|
function initials(name) { return name.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase(); }
|
|
function pct(val, total) { return total > 0 ? (val / total * 100).toFixed(1) : 0; }
|
|
|
|
const state = {
|
|
selectedDev: 'all',
|
|
selectedPeriod: '90d'
|
|
};
|
|
|
|
// ── INIT ───────────────────────────────────────────────────────────────────
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
// Load from localStorage
|
|
const savedDev = localStorage.getItem('dash_selectedDev');
|
|
const savedPeriod = localStorage.getItem('dash_selectedPeriod');
|
|
if (savedDev) state.selectedDev = savedDev;
|
|
if (savedPeriod) state.selectedPeriod = savedPeriod;
|
|
|
|
document.getElementById('refreshBtn').addEventListener('click', () => loadAndRender(true));
|
|
|
|
document.getElementById('devFilter').addEventListener('change', (e) => {
|
|
state.selectedDev = e.target.value;
|
|
localStorage.setItem('dash_selectedDev', state.selectedDev);
|
|
renderCurrentSection();
|
|
renderHistorySection();
|
|
});
|
|
|
|
document.getElementById('timeRangeFilter').addEventListener('change', (e) => {
|
|
state.selectedPeriod = e.target.value;
|
|
localStorage.setItem('dash_selectedPeriod', state.selectedPeriod);
|
|
loadAndRender(false);
|
|
});
|
|
|
|
// Set initial value in UI from state (which might come from localStorage)
|
|
const periodFilter = document.getElementById('timeRangeFilter');
|
|
if (periodFilter) periodFilter.value = state.selectedPeriod;
|
|
|
|
loadAndRender();
|
|
});
|
|
|
|
async function loadAndRender(forceRefresh = false) {
|
|
const loading = document.getElementById('loadingOverlay');
|
|
const errorBanner = document.getElementById('errorBanner');
|
|
loading.style.display = 'flex';
|
|
errorBanner.style.display = 'none';
|
|
document.getElementById('refreshBtn').disabled = true;
|
|
|
|
try {
|
|
const data = await api.fetchDashboardData(forceRefresh, state.selectedPeriod);
|
|
|
|
const limitBanner = document.getElementById('limitBanner');
|
|
if (data.isTruncated) {
|
|
limitBanner.style.display = 'block';
|
|
limitBanner.textContent = `⚠️ Advertencia de límite: Solo se procesaron 1500 tickets en este período debido a las políticas de seguridad (Total real encontrado: ${data.jiraTotal}). Reducí el rango de fechas para ver el detalle exacto.`;
|
|
} else {
|
|
limitBanner.style.display = 'none';
|
|
}
|
|
|
|
buildFilters(data);
|
|
renderHeader(data);
|
|
renderHealthWarnings(data.warnings);
|
|
|
|
renderCurrentSection();
|
|
renderHistorySection();
|
|
|
|
} catch(e) {
|
|
errorBanner.style.display = 'block';
|
|
errorBanner.textContent = '⚠️ Error al cargar datos: ' + e.message;
|
|
} finally {
|
|
loading.style.display = 'none';
|
|
document.getElementById('refreshBtn').disabled = false;
|
|
}
|
|
}
|
|
|
|
// ── FILTERS & HEADER ───────────────────────────────────────────────────────
|
|
function buildFilters(data) {
|
|
const devsSet = new Set();
|
|
|
|
data.issuesList.forEach(issue => {
|
|
issue.devs.forEach(d => devsSet.add(d));
|
|
});
|
|
|
|
const devSel = document.getElementById('devFilter');
|
|
devSel.innerHTML = '<option value="all">Todos los desarrolladores</option>'
|
|
+ [...devsSet].sort().map(d => `<option value="${d}">${d}</option>`).join('');
|
|
devSel.value = state.selectedDev;
|
|
}
|
|
|
|
function renderHeader(data) {
|
|
const d = new Date(data.lastUpdated);
|
|
document.getElementById('lastUpdatedLabel').textContent =
|
|
'Actualizado: ' + d.toLocaleString('es-AR', { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' });
|
|
document.getElementById('cacheBadge').textContent = data.fromCache ? '(desde caché)' : '(CACHE)';
|
|
}
|
|
|
|
function getJiraUrl(key) {
|
|
const host = api.data?.config?.host || 'invera.atlassian.net';
|
|
return `https://${host}/browse/${key}`;
|
|
}
|
|
|
|
// ── HEALTH WARNINGS ────────────────────────────────────────────────────────
|
|
function renderHealthWarnings(warnings = []) {
|
|
const container = document.getElementById('warningsSection');
|
|
const list = document.getElementById('warningsList');
|
|
const noMsg = document.getElementById('noWarningsMsg');
|
|
|
|
if(!warnings || warnings.length === 0) {
|
|
container.style.display = 'none';
|
|
if (noMsg) noMsg.style.display = 'block';
|
|
return;
|
|
}
|
|
|
|
container.style.display = 'block';
|
|
if (noMsg) noMsg.style.display = 'none';
|
|
|
|
list.innerHTML = warnings.map(w => {
|
|
let text = '';
|
|
let badge = w.type;
|
|
const link = `<a href="${getJiraUrl(w.key)}" target="_blank" class="jira-link">${w.key}</a>`;
|
|
|
|
if(w.type === 'stalled') { badge = 'ESTANCADO'; text = `🎟️ [${link}] ${w.summary.slice(0,50)}... (${w.devs.join(', ')})`; }
|
|
if(w.type === 'done_no_sp') { badge = 'SIN SP'; text = `🎟️ [${link}] ${w.summary.slice(0,50)}... (Completado sin estimación)`; }
|
|
if(w.type === 'unassigned_sp') { badge = 'HUÉRFANO'; text = `🎟️ [${link}] ${w.summary.slice(0,50)}... (${w.sp} SP sin dueño)`; }
|
|
|
|
return `<li class="warning-item" title="${w.summary}"><span class="badge" style="width:90px;text-align:center;">${badge}</span> <span class="title" style="font-size:11px;">${text}</span></li>`;
|
|
}).join('');
|
|
}
|
|
|
|
// ── CURRENT SECTION (Interactive filtered) ─────────────────────────────────
|
|
function renderCurrentSection() {
|
|
const data = api.data;
|
|
if (!data) return;
|
|
|
|
// 1. Filtrar solo pendientes (En progreso o To Do) + Filtro de Dev
|
|
let allPending = data.issuesList.filter(i => i.status !== 'done');
|
|
|
|
// Para el label "Mostrando X de Y", filtramos por Dev
|
|
let filtered = allPending;
|
|
if (state.selectedDev !== 'all') {
|
|
filtered = allPending.filter(i => i.devs.includes(state.selectedDev));
|
|
}
|
|
|
|
// Agrupar métricas para los KPIs (basado en el filtro de Dev)
|
|
const ad = {};
|
|
let totalDevs = new Set();
|
|
|
|
filtered.forEach(i => {
|
|
i.devs.forEach(dev => {
|
|
if(state.selectedDev !== 'all' && dev !== state.selectedDev) return;
|
|
if (!ad[dev]) ad[dev] = { in_progress: 0, todo: 0, issues_ip: [], issues_todo: [] };
|
|
|
|
if (i.status === 'indeterminate') {
|
|
ad[dev].in_progress += i.sp;
|
|
ad[dev].issues_ip.push(i);
|
|
} else {
|
|
ad[dev].todo += i.sp;
|
|
ad[dev].issues_todo.push(i);
|
|
}
|
|
totalDevs.add(dev);
|
|
});
|
|
});
|
|
|
|
let ip = 0, todo = 0;
|
|
Object.values(ad).forEach(d => { ip += d.in_progress; todo += d.todo; });
|
|
|
|
document.getElementById('kpi-ip').textContent = ip;
|
|
document.getElementById('kpi-todo').textContent = todo;
|
|
document.getElementById('kpi-members').textContent = totalDevs.size;
|
|
|
|
// Conteo de tickets
|
|
const label = document.getElementById('currentTicketsLabel');
|
|
if (label) {
|
|
label.textContent = state.selectedDev === 'all'
|
|
? `Hay ${allPending.length} tickets pendientes en total`
|
|
: `Mostrando ${filtered.length} tickets pendientes para ${state.selectedDev}`;
|
|
}
|
|
|
|
// Gráfico: Comparativa IP vs Todo (Stacked)
|
|
const people = Object.keys(ad).sort((a,b) => (ad[b].in_progress+ad[b].todo)-(ad[a].in_progress+ad[a].todo));
|
|
chartsManager.drawBarChart('currentState', 'chartCurrentState', people.map(shortName), [
|
|
{ label:'En Progreso', data:people.map(p=>ad[p].in_progress), backgroundColor:'#0065ff', borderRadius:3 },
|
|
{ label:'Por Hacer', data:people.map(p=>ad[p].todo), backgroundColor:'#ff8b00', borderRadius:3 },
|
|
], { plugins:{ legend:{ position:'bottom'} }, scales:{ x:{stacked:true,grid:{display:false}}, y:{stacked:true} } });
|
|
|
|
// Tabla detallada (Solo pendientes)
|
|
const tbody = document.getElementById('tableCurrentState');
|
|
tbody.innerHTML = '';
|
|
people.forEach(p => {
|
|
const d = ad[p], total = d.in_progress + d.todo;
|
|
const c = chartsManager.personColor(p);
|
|
|
|
const tooltipIP = d.issues_ip.map(i => `${i.key} (${i.sp} SP)`).join('\n');
|
|
const tooltipTodo = d.issues_todo.map(i => `${i.key} (${i.sp} SP)`).join('\n');
|
|
const allKeys = [...d.issues_ip, ...d.issues_todo].map(i =>
|
|
`<a href="${getJiraUrl(i.key)}" target="_blank" class="jira-link-small" title="${i.summary}">${i.key}</a>`
|
|
).join(' ');
|
|
|
|
tbody.innerHTML += `<tr>
|
|
<td>
|
|
<div class="name-cell"><div class="avatar" style="background:${c}">${initials(p)}</div>${p}</div>
|
|
<div class="ticket-list-inline">${allKeys}</div>
|
|
</td>
|
|
<td><span class="pill progress" title="${tooltipIP}">${d.in_progress} SP</span></td>
|
|
<td><span class="pill todo" title="${tooltipTodo}">${d.todo} SP</span></td>
|
|
<td><strong>${total} SP</strong></td>
|
|
<td><div class="pbar-wrap">
|
|
<div class="pbar-ip" style="width:${pct(d.in_progress, total)}%"></div>
|
|
<div class="pbar-todo" style="width:${pct(d.todo, total)}%"></div>
|
|
</div></td>
|
|
</tr>`;
|
|
});
|
|
}
|
|
|
|
// ── HISTORY SECTION ────────────────────────────────────────────────────────
|
|
function renderHistorySection() {
|
|
const data = api.data;
|
|
if(!data) return;
|
|
|
|
// Consolidar todos los meses del rango actual
|
|
let periodData = {};
|
|
Object.values(data.monthlyDone).forEach(md => {
|
|
Object.entries(md).forEach(([p, sp]) => {
|
|
if (state.selectedDev !== 'all' && p !== state.selectedDev) return;
|
|
periodData[p] = (periodData[p] || 0) + sp;
|
|
});
|
|
});
|
|
|
|
const totalSP = Object.values(periodData).reduce((a,b) => a+b, 0);
|
|
const devCount = Object.keys(periodData).filter(p => periodData[p] > 0).length;
|
|
|
|
document.getElementById('kpi-done-period').textContent = totalSP;
|
|
document.getElementById('kpi-devs-period').textContent = devCount;
|
|
document.getElementById('kpi-avg-period').textContent = devCount > 0 ? Math.round(totalSP / devCount) : 0;
|
|
|
|
// Gráfico de impacto personal (Terminados)
|
|
const sorted = Object.entries(periodData).filter(([,sp]) => sp > 0).sort((a,b) => b[1]-a[1]);
|
|
chartsManager.drawBarChart('doneDev', 'chartDoneDev', sorted.map(([p]) => shortName(p)), [{
|
|
label: 'SP entregados', data: sorted.map(([,sp]) => sp),
|
|
backgroundColor: sorted.map(([p]) => chartsManager.personColor(p)), borderRadius: 5
|
|
}], { plugins:{ legend:{ display:false } }, scales:{ x:{grid:{display:false}} } });
|
|
|
|
// Tabla de Resultados
|
|
const tbody = document.getElementById('tableHistory');
|
|
tbody.innerHTML = '';
|
|
if (sorted.length === 0) {
|
|
tbody.innerHTML = '<tr><td colspan="3" class="no-data">No hay entregas en este período</td></tr>';
|
|
} else {
|
|
sorted.forEach(([p, sp]) => {
|
|
const p_ = totalSP > 0 ? (sp / totalSP * 100).toFixed(1) : 0;
|
|
const c = chartsManager.personColor(p);
|
|
tbody.innerHTML += `<tr>
|
|
<td><div class="name-cell"><div class="avatar" style="background:${c}">${initials(p)}</div>${p}</div></td>
|
|
<td><span class="pill done">${sp} SP entregados</span></td>
|
|
<td><div style="display:flex;align-items:center;gap:8px;">
|
|
<div style="background:#f0f2f5;border-radius:4px;height:8px;width:120px;overflow:hidden;">
|
|
<div style="background:#36b37e;height:100%;width:${p_}%"></div>
|
|
</div><span style="font-size:12px;color:#5e6c84;">${p_}%</span></div></td>
|
|
</tr>`;
|
|
});
|
|
}
|
|
|
|
// Gráfico de Velocidad Mensual
|
|
const months = Object.keys(data.monthlyDone).sort();
|
|
const allDevsInHistory = [...new Set(months.flatMap(m => Object.keys(data.monthlyDone[m])))];
|
|
|
|
// Si hay filtro de dev, solo mostrar ese dev en el gráfico de velocidad
|
|
const visibleDevs = state.selectedDev === 'all' ? allDevsInHistory : [state.selectedDev];
|
|
|
|
chartsManager.drawBarChart('velocity', 'chartVelocity', months, visibleDevs.map(p => ({
|
|
label: shortName(p),
|
|
data: months.map(m => data.monthlyDone[m][p] || 0),
|
|
backgroundColor: chartsManager.personColor(p), borderRadius: 3
|
|
})), { plugins:{ legend:{ position:'bottom'} }, scales:{ x:{stacked:true,grid:{display:false}}, y:{stacked:true} } });
|
|
}
|