feat: Números measures the site and the Prumo (0.12)

The browser records page load, upload speed and bytes, Prumo's check and
the loose-art montage; the quote keeps them and Números shows average and
p95 per period. Print generation and the payment-to-card time come from
the database. The upload bar already estimates its remaining time.
This commit is contained in:
Cauê Faleiros
2026-11-06 11:09:36 -03:00
parent 945c9e366a
commit 6351a094f4
11 changed files with 170 additions and 3 deletions

View File

@@ -146,13 +146,16 @@
const k=chaveArquivo(file);
let e=envios.get(k);
if (!e) {
const T=window.dtfTimings;
if(T){ if(T.uploadStart==null)T.uploadStart=performance.now();
if(!T.uploadSeen.has(k)){T.uploadSeen.add(k);T.uploadBytes+=file.size;} }
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
e.promise=(async()=>{
const session=await ready;
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
onBytes:n=>{e.sent=n;pintaEnvio();}});
})();
e.promise.then(()=>{e.done=true;falhas.delete(k);pintaEnvio();},
e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();},
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
envios.set(k,e);
}
@@ -370,13 +373,24 @@
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
if ($('fProva')?.checked) content.proof = true;
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
const serialized = JSON.stringify(content);
// Browser timings for Números (item 0.12); they never affect the price.
const T=window.dtfTimings, timings={};
const nav=performance.getEntriesByType?.('navigation')?.[0];
const pageMs=nav?.domContentLoadedEventEnd || (T?.pageStart!=null?performance.now()-T.pageStart:0);
if(pageMs>0)timings.page_ms=Math.round(pageMs);
if(T?.uploadStart!=null&&T.uploadEnd!=null){
timings.upload_ms=Math.round(T.uploadEnd-T.uploadStart);
timings.upload_bytes=Math.round(T.uploadBytes||0);
}
if(T?.analysisStart!=null&&T.analysisEnd!=null)timings.analysis_ms=Math.round(T.analysisEnd-T.analysisStart);
if(T?.montageStart!=null&&T.montageEnd!=null)timings.montage_ms=Math.round(T.montageEnd-T.montageStart);
const serialized = JSON.stringify({...content,timings});
if (!requestKey || serialized !== requestBody) {
requestKey = crypto.randomUUID(); requestBody = serialized;
localStorage.setItem('dtf-request-key',requestKey);
localStorage.setItem('dtf-request-body',requestBody);
}
const quote = await api('/quotes',{request_key:requestKey,...content});
const quote = await api('/quotes',{request_key:requestKey,...content,timings});
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
await refresh(true);

View File

@@ -142,6 +142,8 @@
<section class="panel clip s6"><div class="phead"><h2>Tempo em cada etapa</h2><span class="hint tip-l" tabindex="0" data-tip="Tempo mediano por pedido: quem voltou para a etapa soma cada passagem. O tempo em Aguardando contato não conta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Mediana</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table></section>
</div>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (MB/s), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>
<section id="tab-users" class="page" hidden>
<section class="panel clip">

View File

@@ -2561,6 +2561,17 @@ async function loadStats(){
tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'),
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==='MB/s'
? (v=>v==null?'—':v.toFixed(1).replace('.',',')+' MB/s')
: (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;}));
}
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

View File

@@ -4,6 +4,12 @@
scope and run top to bottom, exactly as the original did. */
const $=id=>document.getElementById(id);
// What the browser measured while the customer built the cart (item 0.12):
// page load, upload, Prumo's check and the loose-art montage. It only feeds
// Números; no price or acceptance depends on it.
window.dtfTimings={pageStart:performance.now(),uploadStart:null,uploadEnd:null,
uploadBytes:0,uploadSeen:new Set(),analysisStart:null,analysisEnd:null,
montageStart:null,montageEnd:null};
const rs=v=>'R$ '+v.toFixed(2).replace('.',',');
// Ícones (Lucide, licença ISC) desenhados no próprio HTML: nada a carregar, e a
// cor vem do texto em volta. Os que ficam no HTML estático são os mesmos.

View File

@@ -493,6 +493,8 @@ function motivoNota(){
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
}
function previa(){
const T=window.dtfTimings;
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
// Na folha pronta o painel não tem o que mostrar: a folha vem fechada, ninguém
// olhou dentro dela. Largura e metragem — o que de fato medimos — já aparecem
// na coluna ao lado e no carrinho.

View File

@@ -68,9 +68,18 @@ function tracoDoItem(lista,layout){
proofSourceIndex:fino.index,
proofYFraction:fracaoNoFilme(lista?layout:montagemLayout,fino.index,fino.traco.proofYFraction||0)};
}
// Fecha a medida da conferência quando não há mais arquivo sendo lido (0.12).
function marcaTempos(){
const T=window.dtfTimings;
if(!T || T.analysisStart==null || T.analysisEnd!=null) return;
if(!(folhas.length+artes.length)) return;
if(folhas.some(x=>x.pct!=null) || artes.some(a=>a.lendoArte)) return;
T.analysisEnd=performance.now();
}
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
// para a fila dizer em texto em vez de travar num botão.
function avaliar(){
marcaTempos();
if(ehFolha()){
if(!folhas.length) return {pronto:false, falta:'Arraste sua folha montada para começar.'};
const pdfInvalido=folhas.find(x=>x.measurementError);

View File

@@ -100,6 +100,10 @@ async function marcaResiduos(x){
}
async function sel(fs){
if(!fs.length) return;
const T=window.dtfTimings;
if(T){const now=performance.now();
if(T.montageStart==null)T.montageStart=now;
if(T.analysisStart==null)T.analysisStart=now;}
fs=await Promise.all(fs.map(nomeReal));
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
// declares it by choosing the product in the selector above. The declaration is