Repository navigation
Expand file tree
/
Copy pathevolution.js
More file actions
13 lines (13 loc) · 4.66 KB
/
Copy pathevolution.js
File metadata and controls
13 lines (13 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
import {ratingSamples,formatRating,ratingLabels} from './ping-rating.js';
import {activeId} from './profiles.js';
import {list} from './database.js';
export function buckets(mode,year,now=new Date()){
const start=new Date(year,0,1),end=new Date(year+1,0,1),out=[];
if(mode==='days'){start.setTime(+now);start.setHours(0,0,0,0);start.setDate(start.getDate()-29);end.setTime(+now);end.setHours(0,0,0,0);end.setDate(end.getDate()+1);}
if(mode==='weeks'){start.setDate(start.getDate()-((start.getDay()+6)%7));if(!ratingLabels(+start)[1].startsWith('Semana 01/'+year+' '))start.setDate(start.getDate()+7);end.setDate(4);end.setDate(end.getDate()-((end.getDay()+6)%7));}
for(let d=new Date(start);d<end;){const a=+d;let label;if(mode==='months'){label=d.toLocaleDateString('pt-BR',{month:'short'});d.setMonth(d.getMonth()+1);}else if(mode==='weeks'){label=ratingLabels(a)[1].split(' ')[1];d.setDate(d.getDate()+7);}else{label=d.toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});d.setDate(d.getDate()+1);}out.push({a,b:+d,label,count:0,sum:0,value:null});}return out;
}
export function aggregate(rows,profile,periods,end){let i=0;for(const {at,n} of ratingSamples(rows,profile,end)){while(i<periods.length&&at>=periods[i].b)i++;if(i===periods.length)break;const p=periods[i];if(at>=p.a){p.count++;p.sum+=Math.round(n*10);}}return periods.map(p=>({...p,value:p.count?p.sum/p.count/10:null}));}
export function evolutionMarkup(){return `<section class="panel evolution"><h2>Evolução das notas</h2><div class="evolution-tools"><label>Período <select id="evolution-mode"><option value="months">Meses do ano</option><option value="weeks">Semanas ISO</option><option value="days">Últimos 30 dias</option></select></label><label>Ano <input id="evolution-year" type="number" min="1970" max="9999" step="1" value="${new Date().getFullYear()}"></label><button id="evolution-load">Consultar</button></div><div id="evolution-chart"></div><small id="evolution-status" role="status"></small><details><summary>Valores e quantidade de notas</summary><div id="evolution-values"></div></details><small class="muted">Médias aritméticas das notas reconstruídas. Lacunas indicam ausência de notas válidas; períodos em andamento são parciais.</small></section>`;}
export function graph(ps){const x=i=>35+i*550/Math.max(1,ps.length-1),y=n=>175-n*15;let lines='',dots='',labels='';ps.forEach((p,i)=>{if(p.value!==null){if(i&&ps[i-1].value!==null)lines+=`<line x1="${x(i-1)}" y1="${y(ps[i-1].value)}" x2="${x(i)}" y2="${y(p.value)}"/>`;dots+=`<circle cx="${x(i)}" cy="${y(p.value)}" r="3"><title>${p.label}: ${formatRating(p.value)} (${p.count} notas)</title></circle>`;}if(i%Math.ceil(ps.length/12)===0||i===ps.length-1)labels+=`<text x="${x(i)}" y="192" text-anchor="middle">${p.label.split('/')[0]}${p.label.includes('/')&&p.label.length===5?'/'+p.label.split('/')[1]:''}</text>`;});return `<svg viewBox="0 0 610 205" role="img" aria-label="Gráfico de notas de zero a dez; valores disponíveis na tabela"><g class="evolution-grid">${[0,2,4,6,8,10].map(n=>`<line x1="35" x2="585" y1="${y(n)}" y2="${y(n)}"/><text x="25" y="${y(n)+4}" text-anchor="end">${n}</text>`).join('')}</g><g class="evolution-line">${lines}${dots}</g><g class="evolution-labels">${labels}</g></svg>`;}
export function mountEvolution(root){const mode=root.querySelector('#evolution-mode'),year=root.querySelector('#evolution-year'),status=root.querySelector('#evolution-status'),chart=root.querySelector('#evolution-chart'),values=root.querySelector('#evolution-values');let rev=0;async function refresh(){const token=++rev;year.disabled=mode.value==='days';if(!year.disabled&&(!year.checkValidity()||!year.value)){status.textContent='Informe um ano válido.';return;}const now=new Date(),ps=buckets(mode.value,Number(year.value),now),profile=activeId();status.textContent='Consultando registros…';chart.innerHTML=values.innerHTML='';try{const end=Math.min(+now+1,ps.at(-1).b),start=ps[0].a;const rows=end>start?await list('measurements',{index:'profileTime',range:IDBKeyRange.bound([profile,start-100000],[profile,end]),limit:Infinity}):[];if(token!==rev||!status.isConnected)return;const data=aggregate(rows,profile,ps,end);chart.innerHTML=graph(data);values.innerHTML='<table><thead><tr><th>Período</th><th>Nota</th><th>Amostras</th></tr></thead><tbody>'+data.map(p=>`<tr><td>${p.label}</td><td>${formatRating(p.value)}</td><td>${p.count.toLocaleString('pt-BR')}</td></tr>`).join('')+'</tbody></table>';status.textContent=data.some(p=>p.count)?'Consulta atualizada.':'Sem notas válidas no período.';}catch(e){if(token===rev&&status.isConnected)status.textContent='Não foi possível consultar os registros.';}}mode.onchange=refresh;root.querySelector('#evolution-load').onclick=refresh;refresh();}