Files
dtf-system/web/kanban-numbers.js
Cauê Faleiros b5a51137fb feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11)
Interno: the Expedição assembles the marketplace's own sales on the fixed
internal customer Gestão fills in once; no Tiny order, no paid e-mail,
marked interno, it stays in house. Venda: a Vendedor or Gestão picks the
customer from the Tiny base and the order goes to Tiny like an approved
quote, faturado (Boleto from TINY_RECEIPT_BOLETO when set), pickup or
'junto com o pedido de roupa nº X'. Números counts both at table price,
apart from cash (and the average ticket over cash orders only). Each stamp
can carry a brand and a public flag for the future catalogue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:01:44 -03:00

343 lines
24 KiB
JavaScript

/* Kanban DTF: the Números tab. The period's numbers and the machines month by
month (front 1b). Loaded after kanban.js, which defines api, node, money,
metres, plural, when, say, $, svgIcon, IC, iconButton, may,
stageLimitsDialog, openPanel, PHONE, board, waitingContact, ORIGINS,
REWORK_CAUSES, REWORK_OUTSIDE and GLYPH. */
// ---- Numbers -------------------------------------------------------------
// The period: the last 7, 30 or 90 days, or two dates picked on the calendar.
let statsDays=30, statsRange=null, statsData=null;
// The machine block has a month of its own, apart from the period above.
let machineMonth=null, machineStats=null, machineStatsMonth=null;
function duration(hours){
if(hours===null||hours===undefined)return '—';
if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
if(hours<48){const h=Math.floor(hours),m=Math.round((hours-h)*60);return m&&h<10?h+' h '+String(m).padStart(2,'0'):Math.round(hours)+' h';}
return Math.round(hours/24)+' dias';
}
const dayLabel=iso=>new Date(iso+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit',year:'numeric'});
const shortDay=iso=>new Date(iso+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
const isoDay=d=>d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');
// Brasília's today, whatever the computer's clock zone.
const todayIso=()=>new Date(Date.now()-3*3600e3).toISOString().slice(0,10);
function statsPeriod(){
const seg=$('stats-period');
seg.replaceChildren(...[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
const on=!statsRange&&days===statsDays;
const b=node('button',label,on?'on':'');b.type='button';b.setAttribute('aria-pressed',String(on));
b.onclick=()=>{statsDays=days;statsRange=null;loadStats().catch(e=>say(e.message,true));};return b;}));
const wrap=$('stats-range');
const open=node('button',undefined,'btn'+(statsRange?' on':''));open.type='button';open.setAttribute('aria-haspopup','dialog');
open.append(svgIcon(IC.calendar,'i m'),statsRange?shortDay(statsRange.start)+' a '+shortDay(statsRange.end):'Escolher datas');
open.onclick=e=>{e.stopPropagation();const pop=wrap.querySelector('.pop');if(pop){pop.remove();return;}wrap.append(calendar());};
wrap.replaceChildren(open);
}
// The calendar: presets on the left, a month where a click starts the
// period and the next one ends it.
function calendar(){
const pop=node('div',undefined,'pop calpop');pop.setAttribute('role','dialog');pop.setAttribute('aria-label','Escolher o período');
pop.onclick=e=>e.stopPropagation();
const today=todayIso();
let pick=statsRange?{...statsRange}:null, month=new Date((statsRange?.end||today)+'T12:00:00');month.setDate(1);
const presets=node('div',undefined,'presets'),grid=node('div',undefined,'dgrid'),title=node('b');
const label=node('span','','lbl');
const apply=node('button','Aplicar','btn pri');apply.type='button';
const cancel=node('button','Cancelar','btn ghost right');cancel.type='button';cancel.onclick=()=>pop.remove();
apply.onclick=()=>{if(!pick?.end)return;statsRange=pick;pop.remove();loadStats().catch(e=>say(e.message,true));};
const back=n=>{const d=new Date(today+'T12:00:00');d.setDate(d.getDate()-n);return isoDay(d);};
const first=new Date(today+'T12:00:00');first.setDate(1);
const prevEnd=new Date(first);prevEnd.setDate(0);const prevStart=new Date(prevEnd);prevStart.setDate(1);
for(const [text,range] of [['Hoje',[today,today]],['Últimos 7 dias',[back(6),today]],['Últimos 30 dias',[back(29),today]],
['Este mês',[isoDay(first),today]],['Mês passado',[isoDay(prevStart),isoDay(prevEnd)]],['Últimos 90 dias',[back(89),today]]]){
const b=node('button',text,'preset');b.type='button';b.dataset.range=range.join('|');
b.onclick=()=>{pick={start:range[0],end:range[1]};month=new Date(range[1]+'T12:00:00');month.setDate(1);paint();};presets.append(b);
}
const prev=iconButton(IC.left,'Mês anterior',()=>{month.setMonth(month.getMonth()-1);paint();},'btn sq ghost');
const next=iconButton(IC.right,'Próximo mês',()=>{month.setMonth(month.getMonth()+1);paint();},'btn sq ghost');
const head=node('div',undefined,'mhd');head.append(title,prev,next);
function paint(){
title.textContent=month.toLocaleDateString('pt-BR',{month:'long',year:'numeric'}).replace(/^./,c=>c.toUpperCase());
next.disabled=isoDay(month)>=today.slice(0,8)+'01';
for(const b of presets.children){const [a,z]=b.dataset.range.split('|');b.classList.toggle('on',!!pick&&pick.start===a&&pick.end===z);}
const days=[...['D','S','T','Q','Q','S','S'].map(w=>node('span',w,'dow'))];
const start=new Date(month);start.setDate(1-start.getDay());
for(let i=0;i<42;i++){
const d=new Date(start);d.setDate(start.getDate()+i);const iso=isoDay(d);
if(i>=35&&d.getMonth()!==month.getMonth())break;
const end=pick?.end||pick?.start;
const cls=['day'];if(d.getMonth()!==month.getMonth())cls.push('mute');if(iso>today)cls.push('future');if(iso===today)cls.push('today');
if(pick&&iso===pick.start)cls.push('s');if(pick&&iso===end)cls.push('e');if(pick&&iso>pick.start&&iso<end)cls.push('in');
const b=node('button',undefined,cls.join(' '));b.type='button';b.append(node('span',String(d.getDate())));
b.setAttribute('aria-label',dayLabel(iso));b.disabled=iso>today;
b.onclick=()=>{if(!pick||pick.end)pick={start:iso,end:null};else if(iso<pick.start)pick={start:iso,end:pick.start};else pick.end=iso;paint();};
days.push(b);
}
grid.replaceChildren(...days);
label.textContent=pick?dayLabel(pick.start)+(pick.end?' a '+dayLabel(pick.end):', escolha o fim'):'Escolha o início';
apply.disabled=!pick?.end;
}
const monthBox=node('div',undefined,'month');monthBox.append(head,grid);
const body=node('div',undefined,'cal');body.append(presets,monthBox);
const foot=node('div',undefined,'popfoot');foot.append(label,cancel,apply);
pop.append(body,foot);paint();
document.addEventListener('click',()=>pop.remove(),{once:true});
return pop;
}
// ---- Máquinas, mês a mês -------------------------------------------------
// This block has its own month: it does not follow the period at the top, so
// it is fetched apart and kept until the month changes.
const MACHINE_MONTHS=['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho',
'Agosto','Setembro','Outubro','Novembro','Dezembro'];
function machineMonthShift(key,delta){
const [year,month]=key.split('-').map(Number),d=new Date(Date.UTC(year,month-1+delta,1));
return d.getUTCFullYear()+'-'+String(d.getUTCMonth()+1).padStart(2,'0');
}
function machineMonthName(key){
const [year,month]=key.split('-').map(Number);
return MACHINE_MONTHS[month-1].toLowerCase()+' de '+year;
}
function machineMonthNav(){
const data=machineStats;if(!data)return;
const current=todayIso().slice(0,7);
const prev=iconButton(IC.left,'Mês anterior',()=>changeMachineMonth(-1));
const next=iconButton(IC.right,'Próximo mês',()=>changeMachineMonth(1));
next.disabled=data.month>=current;
$('stats-machine-nav').replaceChildren(prev,node('b',machineMonthName(data.month)),next);
}
function changeMachineMonth(delta){
const current=todayIso().slice(0,7);
machineMonth=machineMonthShift(machineMonth||current,delta);
if(machineMonth>current)machineMonth=current;
loadMachineStats().catch(e=>say(e.message,true));
}
async function loadMachineStats(){
const month=machineMonth||todayIso().slice(0,7);
if(machineStats&&machineStatsMonth===month){renderMachineStats();return;}
const data=await api('/stats/machines?month='+month);
machineStats=data;machineStatsMonth=month;renderMachineStats();
}
function renderMachineStats(){
const data=machineStats;if(!data)return;
machineMonthNav();
const machines=data.machines,one=v=>v==null?'—':Number(v).toLocaleString('pt-BR',
{minimumFractionDigits:1,maximumFractionDigits:1}),unit=(v,u)=>v==null?'—':one(v)+u,
cash=v=>v==null?'—':money(v);
const head=node('tr');head.append(node('th','Indicador'));
for(const m of machines){const th=node('th',m.name,'r');th.scope='col';head.append(th);}
$('stats-machine-head').replaceChildren(head);
const stopsTitle=m=>(m.month.stops||[]).map(s=>(s.reason||'Parada')+' '+one(s.hours)+' h').join('; ');
const groups=[
['Produção',[
['Metros impressos',m=>m.month.printed_metres==null?'—':metres(m.month.printed_metres)],
['Metros por hora',m=>unit(m.month.metres_per_hour,' m/h')],
['Horas rodando',m=>unit(m.month.hours_running,' h')],
['Horas paradas',m=>unit(m.month.stopped_hours,' h'),stopsTitle]]],
['Consumo',[
['Metros por rolo de filme',m=>unit(m.month.metres_per_roll,' m')],
...['ink_c','ink_m','ink_y','ink_k','ink_w'].map(item=>
['Tinta '+{ink_c:'ciano',ink_m:'magenta',ink_y:'amarela',ink_k:'preta',ink_w:'branca'}[item]+' por 100 m',
m=>unit(m.month.ink_per_100m[item],' L')]),
['Poliamida por 100 m',m=>unit(m.month.powder_g_per_100m,' g')]]],
['Custo',[
['Insumos por metro',m=>cash(m.month.supplies_per_metre_cents)],
['Peças por metro',m=>cash(m.month.parts_per_metre_cents)],
['Total por metro',m=>cash(m.month.total_per_metre_cents)]]],
['Resultado',[
['Vendido',m=>cash(m.month.sold_cents)],
['Contribuição do mês',m=>cash(m.month.contribution_cents)],
['Contribuição desde a instalação',m=>cash(m.total.contribution_cents)]]],
['Retorno',[
['Retorno (%)',m=>m.total.roi_pct==null?'—':one(m.total.roi_pct)+'%'],
['Meses para se pagar',m=>one(m.total.payback_months)]]]];
const body=$('stats-machine-body');
if(!machines.length){body.replaceChildren(emptyRow('Nenhuma máquina com números neste mês.',1));}
else{
const rows=[];
for(const [label,items] of groups){
const group=node('tr',undefined,'group'),cell=node('td',label);cell.colSpan=machines.length+1;
group.append(cell);rows.push(group);
for(const [name,value,title] of items){
const tr=node('tr');tr.append(node('td',name));
for(const m of machines){const td=node('td',value(m),'r'),tip=title&&title(m);if(tip)td.title=tip;tr.append(td);}
rows.push(tr);
}
}
body.replaceChildren(...rows);
}
const missing=machines.some(m=>m.price_cents==null);
$('stats-machine-note').textContent='Os custos vêm dos lançamentos na ficha de cada máquina; '
+'preço e data de instalação vêm de Dados da máquina.'
+(missing?' Sem o preço de compra, o retorno fica em branco.':'');
}
async function loadStats(){
loadMachineStats().catch(e=>say(e.message,true));
const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays));
const editLimits=$('edit-stage-limits');
if(editLimits){editLimits.hidden=!may('manage');editLimits.onclick=()=>stageLimitsDialog();}
statsData=data;statsPeriod();
$('stats-note').textContent='Pedidos pagos de '+dayLabel(data.start)+' a '+dayLabel(data.end)+', sem testes e cancelados';
const hk=(label,value,unit,note)=>{const k=node('div',undefined,'hk');const b=node('b',value);if(unit)b.append(node('small',unit));
k.append(node('span',label),b,...(note?[node('em',note)]:[]));return k;};
const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;};
const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':'';
const [reais,centavos]=money(data.cents).split(',');
// The ticket is the cash received over the cash orders only: an Interno or
// faturado order records the table price, not money received (front 7a.3).
const cashOrders=Math.max(0,Number(data.orders)-(data.price_table||[]).reduce((sum,row)=>sum+(row.orders||0),0));
const hero=node('div',undefined,'hero');
hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')),
hk('Recebido, com frete',reais,','+centavos,cashOrders?'ticket médio de '+money(Math.round(data.cents/cashOrders)):''),
hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período'));
const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%';
const minis=node('div',undefined,'minis');
minis.append(mk('Pedidos pagos',String(data.orders)),
mk('Ticket médio',cashOrders?money(Math.round(data.cents/cashOrders)):'—'),
mk('Com correção',String(data.corrected),pct(data.corrected)),
mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)),
mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)),
mk('Aguardando contato',String(board.orders.filter(waitingContact).length),'agora'));
$('stats-kpis').replaceChildren(hero,minis);
statsChart($('stats-chart'),data.daily);
// Por máquina: what each printed, how fast, and what it has now.
const cap=board.printing_cap||2;
const machineRows=data.machines.map(m=>{
const tr=node('tr');if(!m.active)tr.classList.add('off');
const name=node('td');name.append(node('b',m.name+(m.active?'':', desativada')),
node('span',(m.orders?plural(m.orders,'pedido','pedidos'):'nada')+(m.last_finished?', último '+when(m.last_finished):''),'sub'));
const now=!m.id?'—':m.now.imp?(m.now.imp>=cap?'cheia':m.now.imp+' imprimindo')+(m.now.tra?', '+m.now.tra+' na fila':''):m.now.tra?m.now.tra+' na fila':'livre';
tr.append(name,node('td',m.orders?metres(m.metres):'—','r'),
node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m':'—','r'),node('td',now,'muted'));
return tr;});
$('stats-machines').replaceChildren(...(machineRows.length?machineRows:[emptyRow('Nenhuma máquina cadastrada.',4)]));
// Each way in apart (D-21): its orders, metres, money and time to Finalizado.
$('stats-origins').replaceChildren(...data.origins.map(o=>{const tr=node('tr');
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'),
node('td',o.finished?duration(o.median_hours):'—','r'));
if(!o.orders)tr.classList.add('off');return tr;}));
// The montador's table price, apart from the money received (front 7a.3).
const priceNames={faturado:'Faturado',interno:'Interno'};
$('stats-price-table').replaceChildren(...(data.price_table||[]).map(p=>{const tr=node('tr');
tr.append(node('td',priceNames[p.method]||p.method),node('td',String(p.orders),'r'),
node('td',metres(p.metres).replace(' m',''),'r'),node('td',money(p.cents),'r'));
if(!p.orders)tr.classList.add('off');return tr;}));
// Approved orders never paid: made, paid, expired and the abandonment rate.
const unpaid=data.unpaid;
const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)],
['Expirados sem pagamento',String(unpaid.expired)],['Aguardando pagamento',String(unpaid.waiting)],
['Taxa de abandono',unpaid.abandon_pct==null?'—':unpaid.abandon_pct.toFixed(1).replace('.',',')+'%']];
$('stats-unpaid').replaceChildren(...unpaidRows.map(([label,value])=>{const tr=node('tr');
tr.append(node('td',label),node('td',value,'r'));return tr;}));
// Who prepared the finals of the period's orders, for the designer's productivity.
const most=Math.max(1,...data.treated.by.map(t=>t.orders));
$('stats-treated').replaceChildren(...(data.treated.by.length?data.treated.by.map(t=>{
const row=node('div',undefined,'byrow'),track=node('span',undefined,'track'),fill=node('i');fill.style.width=(100*t.orders/most)+'%';track.append(fill);
row.append(node('span',t.who),track,node('b',String(t.orders)));return row;}):[node('p','Nenhuma arte tratada no período.','empty')]));
// Rework (D-02 to D-04): authorized metres redone over the film printed, against the goal.
const scale=Math.max(rw.goal_percent*2,...rw.causes.map(r=>r.percent||0))*1.15||1;
const meter=(value,goal)=>{const m=node('span',undefined,'meter'),track=node('span',undefined,'track'),fill=node('span',undefined,'fill'+(goal!=null&&value>goal?' warn':''));
fill.style.width=Math.min(100,100*(value||0)/scale)+'%';track.append(fill);
if(goal!=null){const g=node('span',undefined,'goal');g.style.left=Math.min(100,100*goal/scale)+'%';track.append(g);}
m.append(track,node('span',share(value),'mv'));return m;};
const reworkRows=rw.causes.map(r=>{const tr=node('tr'),outside=r.cause===REWORK_OUTSIDE;
const cause=node('td');cause.append(REWORK_CAUSES[r.cause]);if(outside)cause.append(node('span','fora da meta','sub'));
const cell=node('td');cell.append(meter(r.percent,outside?null:rw.goal_percent));
tr.append(cause,node('td',metres(r.metres),'r'),cell);if(!r.metres)tr.classList.add('off');return tr;});
const house=node('tr',undefined,'total');const hc=node('td');hc.append(meter(rw.house.percent,rw.house.goal_percent));
house.append(node('td','Total da casa'),node('td',metres(rw.house.metres),'r'),hc);
$('stats-rework').replaceChildren(...reworkRows,house);
$('stats-rework-film').textContent='Do impresso ('+metres(rw.film_metres)+'), contra a meta de '+share(rw.goal_percent);
const pending=$('stats-rework-pending-pill');pending.hidden=!rw.pending.length;
pending.replaceChildren(node('span',undefined,'dot'),plural(rw.pending.length,'aguardando autorização','aguardando autorização'));
const printers=rw.by_printer.map(p=>{const tr=node('tr');tr.append(node('td',p.who),node('td',metres(p.metres),'r'));return tr;});
$('stats-rework-printers').replaceChildren(...(printers.length?printers:[emptyRow('Nenhum retrabalho da casa autorizado no período.',2)]));
$('stats-rework-pending').replaceChildren(...(rw.pending.length?rw.pending.map(p=>{const li=node('li');
const open=node('button','#'+p.number,'linkbtn');open.type='button';open.onclick=()=>openPanel(p.order_id);
li.append(open,' '+REWORK_CAUSES[p.cause]+', '+metres(p.metres)+', aberto por '+p.opened_by+' em '+when(p.opened_at));return li;}):[node('li','Nenhum.','empty')]));
$('stats-stages').replaceChildren(...['rec','tra','imp','cor','rev'].map(state=>{
const tr=node('tr'),name=node('td'),line=node('span',undefined,'stagecell');
line.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')),board.states[state]);name.append(line);
const st=data.stages[state], now=data.waiting[state];
const limit=data.stage_limits?.[state], late=data.late?.[state]||{count:0,today:0};
// Orders; when some came back to the stage, how many times it was entered.
const passed=st?plural(st.orders,'pedido','pedidos')+(st.passages>st.orders?', '+st.passages+' passagens':''):'nenhum';
name.append(node('span',passed,'sub'));
tr.append(name,node('td',st?duration(st.average_hours):'—','r strong'),
node('td',limit?duration(limit.hours):'—','r'),
node('td',late.count?String(late.count)+(late.today?' · '+late.today+' hoje':''):'—','r'),
node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted'));
return tr;}));
// Speed (item 0.12): average and p95 of what the customer feels.
const secs=v=>v==null?'—':v<60?Math.max(1,Math.round(v))+' s':Math.round(v/60)+' min';
const speedFmt=s=>s.unit==='s/MB'
? (v=>v==null?'—':v.toFixed(1).replace('.',',')+' s/MB')
: (v=>s.unit==='s'?secs(v):String(v));
$('stats-speed').replaceChildren(...(data.speed||[]).map(s=>{
const tr=node('tr'),fmt=speedFmt(s);
tr.append(node('td',s.label),node('td',fmt(s.average),'r'),node('td',fmt(s.p95),'r'),
node('td',String(s.samples),'r'));
if(!s.samples)tr.classList.add('off');
return tr;}));
// Coupons of the period (front 8.3): the page's sections live in the HTML,
// so this panel is built here once and kept beside "Pedidos sem pagamento".
let couponPanel=$('stats-coupons-panel');
if(!couponPanel){
couponPanel=node('section',undefined,'panel clip');couponPanel.id='stats-coupons-panel';
const head=node('div',undefined,'phead');head.append(node('h2','Cupons'));
const table=node('table',undefined,'table');
const thead=node('thead'),headRow=node('tr');
for(const [label,cls] of [['Cupom',''],['Pedidos','r'],['Metros','r'],['Desconto','r'],['Recebido','r']])
headRow.append(node('th',label,cls));
thead.append(headRow);
const tbody=node('tbody');tbody.id='stats-coupons';
table.append(thead,tbody);
couponPanel.append(head,node('p','Cupons usados pelos pedidos pagos do período.','phint'),table);
const anchor=$('stats-unpaid')?.closest('section');
if(anchor)anchor.after(couponPanel);else $('tab-stats').append(couponPanel);
}
const couponRows=data.coupons||[];
$('stats-coupons').replaceChildren(...(couponRows.length?couponRows.map(coupon=>{
const tr=node('tr');
tr.append(node('td',coupon.code),node('td',String(coupon.orders),'r'),
node('td',metres(coupon.metres).replace(' m',''),'r'),
node('td',money(coupon.discount_cents),'r'),node('td',money(coupon.cents),'r'));
return tr;}):[emptyRow('Nenhum cupom usado no período.',5)]));
}
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
// Metres per day: one series of columns from one baseline, the period's
// average as a dashed line, today in full; the same numbers as a table below.
function statsChart(box,daily){
const max=Math.max(...daily.map(d=>d.metres),0);
const step=max<=0?1:(()=>{const raw=max/3, 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 avg=daily.length?daily.reduce((t,d)=>t+d.metres,0)/daily.length:0;
const today=todayIso();
const chart=node('div',undefined,'chart'),yaxis=node('div',undefined,'yaxis'),plot=node('div',undefined,'plot');
yaxis.setAttribute('aria-hidden','true');
for(let v=0;v<=ceiling+1e-9;v+=step){const at=100*v/ceiling+'%';
const t=node('span',v.toLocaleString('pt-BR'));t.style.bottom=at;yaxis.append(t);
if(v>0){const g=node('span',undefined,'gl');g.style.bottom=at;plot.append(g);}}
if(avg>0){const a=node('span',undefined,'avg');a.style.bottom=100*avg/ceiling+'%';plot.append(a);}
const bars=node('div',undefined,'bars'),axis=node('div',undefined,'axis');axis.setAttribute('aria-hidden','true');
bars.style.gridTemplateColumns=axis.style.gridTemplateColumns='repeat('+daily.length+',minmax(0,1fr))';
// A phone has room for fewer dates under the bars.
const every=Math.ceil(daily.length/(PHONE.matches?5:10));
daily.forEach((d,i)=>{
const b=node('span',undefined,'bar'+(d.day===today?' now':''));b.style.height=(d.metres>0?Math.max(1,100*d.metres/ceiling):0)+'%';
b.style.animationDelay=Math.min(i*12,400)+'ms';
b.dataset.tip=shortDay(d.day)+': '+metres(d.metres)+', '+plural(d.orders,'pedido','pedidos');
if(i<3)b.classList.add('tip-r');else if(i>daily.length-4)b.classList.add('tip-l');
bars.append(b);axis.append(node('span',(daily.length-1-i)%every===0?shortDay(d.day):''));
});
plot.append(bars,axis);
plot.setAttribute('role','img');plot.setAttribute('aria-label','Metros vendidos por dia, '+daily.length+' dias, média de '+metres(avg));
chart.append(yaxis,plot);
$('stats-legend').replaceChildren(...[['lg-avg','média de '+metres(avg)],['lg-now','hoje']].map(([c,t])=>{const s=node('span');s.append(node('i',undefined,c),t);return s;}));
const table=node('details',undefined,'charttable');table.append(node('summary','Ver em tabela'));
const t=node('table',undefined,'table');const head=node('tr');head.append(node('th','Dia'),node('th','Pedidos','r'),node('th','Metros','r'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const d of [...daily].reverse()){const tr=node('tr');tr.append(node('td',dayLabel(d.day)),node('td',String(d.orders),'r'),node('td',metres(d.metres),'r'));tbody.append(tr);}
t.append(thead,tbody);table.append(t);
box.replaceChildren(chart,table);
}