feat: a Números tab with the production numbers the board already records

Every paid order and every move is recorded, but nobody could see the
totals. The new tab shows, for the last 7, 30 or 90 days: paid orders,
metres sold, money received, the average ticket, how many orders needed a
correction, and the median time from payment to Finalizado. A column per
day charts the metres sold (with a table under it), and a table gives each
stage's median time and what waits in it now, with the oldest order.
Test and cancelled orders stay out.

The header now has five tabs: the search box narrows first, the refresh
picker keeps its width, and the operator's e-mail moves to Sair's tooltip
on narrower screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-05 12:01:03 -03:00
parent f567e6da89
commit 1b445f0459
5 changed files with 183 additions and 10 deletions

View File

@@ -253,18 +253,18 @@ async function load(quiet=false){
function showTab(name){
tab=name;
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
for(const id of ['board','quotes','payments','integrations'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
for(const id of ['board','quotes','payments','stats','integrations'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
$('who').textContent=board.operator||'';
$('who').textContent=board.operator||'';$('logout').title=board.operator?'Sair ('+board.operator+')':'Sair';
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
tinyHeader();renderBoard();renderIntegrations();
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
}
@@ -759,6 +759,75 @@ function historySection(order,rows,section){
section.replaceChildren(node('p','Histórico','eyebrow'),list);
}
// ---- Numbers -------------------------------------------------------------
let statsDays=30;
function duration(hours){
if(hours===null||hours===undefined)return '—';
if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
if(hours<48)return (hours<10?hours.toFixed(1):Math.round(hours).toString()).replace('.',',')+' h';
return Math.round(hours/24)+' dias';
}
async function loadStats(){
const data=await api('/stats?days='+statsDays);
$('stats-period').replaceChildren(...[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(days===statsDays));
b.onclick=()=>{statsDays=days;loadStats().catch(e=>say(e.message,true));};return b;}));
const kpi=(label,value,note)=>{const k=node('div',undefined,'kpi');k.append(node('span',label),node('b',value));if(note)k.append(node('small',note));return k;};
const pct=data.orders?Math.round(100*data.corrected/data.orders):0;
$('stats-kpis').replaceChildren(
kpi('Pedidos pagos',String(data.orders)),
kpi('Metros vendidos',metres(data.metres)),
kpi('Recebido',money(data.cents),'com frete'),
kpi('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
kpi('Pedidos com correção',String(data.corrected),data.orders?pct+'% dos pedidos':null),
kpi('Do pagamento ao Finalizado',duration(data.lead.median_hours),data.lead.orders?'mediana de '+data.lead.orders+' pedidos':'nenhum finalizado'));
statsChart($('stats-chart'),data.daily);
const rows=['rec','tra','fil','imp','cor'].map(state=>{
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
name.append(sw,board.states[state]);
const st=data.stages[state], now=data.waiting[state];
tr.append(name,node('td',st?duration(st.median_hours):'—'),node('td',st?String(st.orders):'0'),
node('td',now?now.orders+(now.orders>1?' pedidos':' pedido')+' · o mais antigo há '+duration(now.oldest_hours):'nenhum'));
return tr;});
$('stats-stages').replaceChildren(...rows);
}
// Metres per day: one series, columns from one baseline, a tooltip per day
// and the same numbers as a table under the chart.
function statsChart(box,daily){
const ns='http://www.w3.org/2000/svg', w=Math.max(320,box.clientWidth||800), h=220, left=44, bottom=26, top=10;
const max=Math.max(...daily.map(d=>d.metres),0);
const step=max<=0?1:(()=>{const raw=max/4, p=10**Math.floor(Math.log10(raw)), f=raw/p;return (f<=1?1:f<=2?2:f<=5?5:10)*p;})();
const ceiling=step*Math.max(1,Math.ceil(max/step));
const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
svg.setAttribute('aria-label','Metros vendidos por dia nos últimos '+daily.length+' dias');
const el=(tag,attrs)=>{const e=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attrs))e.setAttribute(k,v);return e;};
const y=v=>top+(h-top-bottom)*(1-v/ceiling);
for(let v=0;v<=ceiling+1e-9;v+=step){
svg.append(el('line',{x1:left,x2:w,y1:y(v),y2:y(v),class:'grid'}));
const t=el('text',{x:left-8,y:y(v)+4,class:'tick','text-anchor':'end'});t.textContent=v.toLocaleString('pt-BR');svg.append(t);
}
const band=(w-left)/daily.length, bar=Math.min(24,Math.max(2,band-2));
const tip=node('div',undefined,'tip');tip.hidden=true;
const label=d=>new Date(d.day+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
const every=Math.ceil(daily.length/8);
daily.forEach((d,i)=>{
const x=left+band*i+(band-bar)/2, top_=y(d.metres), base=y(0), r=Math.min(4,bar/2,base-top_);
if(d.metres>0)svg.append(el('path',{class:'bar',d:`M${x},${base}V${top_+r}Q${x},${top_} ${x+r},${top_}H${x+bar-r}Q${x+bar},${top_} ${x+bar},${top_+r}V${base}Z`}));
if((daily.length-1-i)%every===0){const t=el('text',{x:x+bar/2,y:h-8,class:'tick','text-anchor':'middle'});t.textContent=label(d);svg.append(t);}
const hit=el('rect',{x:left+band*i,y:top,width:band,height:h-top-bottom,class:'hit'});
hit.onmouseenter=()=>{tip.hidden=false;tip.textContent=label(d)+' · '+d.orders+(d.orders===1?' pedido':' pedidos')+' · '+metres(d.metres);
tip.style.left=(100*(x+bar/2)/w)+'%';tip.style.top=(100*Math.min(top_,base-4)/h)+'%';};
hit.onmouseleave=()=>{tip.hidden=true;};
svg.append(hit);
});
const table=node('details',undefined,'charttable');table.append(node('summary','Ver em tabela'));
const t=node('table',undefined,'log');const head=node('tr');head.append(node('th','Dia'),node('th','Pedidos'),node('th','Metros'));t.append(head);
for(const d of [...daily].reverse()){const tr=node('tr');tr.append(node('td',label(d)),node('td',String(d.orders)),node('td',metres(d.metres)));t.append(tr);}
table.append(t);
box.replaceChildren(svg,tip,table);
}
// ---- Quotes --------------------------------------------------------------
function quoteMetres(q){return (q.approved||q.draft).items.reduce((s,i)=>s+Number(i.billed_metres||i.metres),0);}