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

@@ -1356,6 +1356,50 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
# Speed (item 0.12): the browser's marks on the way to a quote, the
# Prumo's print generation and the time from payment event to card.
site_speed = c.execute(f'''WITH samples AS (
SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms,
(o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms,
(o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes,
(o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms,
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
SELECT
percentile_cont(0.5) WITHIN GROUP (ORDER BY page_ms) AS page_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY (upload_bytes/1048576.0)/(upload_ms/1000.0))
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_bytes/1048576.0)/(upload_ms/1000.0))
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95,
count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY montage_ms) AS montage_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n
FROM samples''', period).fetchone()
print_speed = c.execute(f'''WITH samples AS (
SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds,
COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric,
(o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres
FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id
WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL
AND p.item_index < jsonb_array_length(o.snapshot->'items'))
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
FILTER (WHERE metres>0) AS per10_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
FILTER (WHERE metres>0) AS per10_p95,
count(*) FILTER (WHERE metres>0) AS per10_n
FROM samples''', period).fetchone()
card_speed = c.execute(f'''WITH samples AS (
SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds
FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text
WHERE {REAL_ORDER} AND {within} GROUP BY o.id)
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n
FROM samples WHERE seconds >= 0''', period).fetchone()
series = []
for offset in range((end - start).days + 1):
day = start + timedelta(days=offset)
@@ -1377,9 +1421,32 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
'median_hours': hours(row['median_hours'])} for row in stages},
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
'speed': speed_figures(site_speed, print_speed, card_speed),
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)}
def speed_figures(site, generation, card):
"""Números' speed block: average and p95, in seconds except upload (MB/s)."""
def pair(avg, p95, n, scale=1):
return {'average': round(float(avg)/scale, 2) if avg is not None else None,
'p95': round(float(p95)/scale, 2) if p95 is not None else None,
'samples': int(n or 0)}
return [
{'key': 'page', 'label': 'Abrir o montador', 'unit': 's',
**pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)},
{'key': 'upload', 'label': 'Subir o arquivo', 'unit': 'MB/s',
**pair(site['upload_avg'], site['upload_p95'], site['upload_n'])},
{'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's',
**pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)},
{'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's',
**pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)},
{'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's',
**pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])},
{'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's',
**pair(card['avg_s'], card['p95_s'], card['n'])},
]
def rework_figures(printed, redone, by_printer, undecided):
"""Números' rework: per cause, the metres redone over the film printed,
against the goal; the house's total against four times it."""

View File

@@ -240,6 +240,19 @@ class Item(StrictModel):
raise ValueError('Resolution warning must be acknowledged')
return self
class ClientTimings(StrictModel):
"""What the browser measured on the way to a quote (item 0.12).
They are only numbers for Números; a cart may send none of them, and the
server never uses them to price or accept an order.
"""
page_ms: int | None = Field(default=None, ge=0, le=600000)
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
class QuoteRequest(StrictModel):
request_key: UUID
customer: Customer
@@ -248,6 +261,8 @@ class QuoteRequest(StrictModel):
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None
@model_validator(mode='after')
def splits_complete(self):

View File

@@ -99,6 +99,8 @@ def approve(c, row, items, reviewer):
'destination': draft.get('destination'),
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))

35
tests/test_speed.py Normal file
View File

@@ -0,0 +1,35 @@
"""Números' speed block: average and p95, in the units the PDF asks for."""
import unittest
from app.api.operator import speed_figures
class SpeedFiguresTests(unittest.TestCase):
def test_formats_seconds_and_upload_speed(self):
site = {'page_avg': 1500, 'page_p95': 3000, 'page_n': 4,
'upload_avg': 2.5, 'upload_p95': 1.5, 'upload_n': 4,
'analysis_avg': 12000, 'analysis_p95': 20000, 'analysis_n': 3,
'montage_avg': 8000, 'montage_p95': 9000, 'montage_n': 2}
generation = {'per10_avg': 90, 'per10_p95': 120, 'per10_n': 5}
card = {'avg_s': 0.4, 'p95_s': 0.9, 'n': 2}
rows = {row['key']: row for row in speed_figures(site, generation, card)}
self.assertEqual(rows['page']['average'], 1.5)
self.assertEqual(rows['page']['p95'], 3.0)
self.assertEqual(rows['upload']['unit'], 'MB/s')
self.assertEqual(rows['analysis']['average'], 12.0)
self.assertEqual(rows['montage']['p95'], 9.0)
self.assertEqual(rows['print']['average'], 90)
self.assertEqual(rows['card']['samples'], 2)
def test_missing_samples_stay_empty(self):
empty = {key: None for key in ('page_avg', 'page_p95', 'page_n', 'upload_avg', 'upload_p95',
'upload_n', 'analysis_avg', 'analysis_p95', 'analysis_n',
'montage_avg', 'montage_p95', 'montage_n')}
generation = {'per10_avg': None, 'per10_p95': None, 'per10_n': 0}
card = {'avg_s': None, 'p95_s': None, 'n': 0}
rows = speed_figures(empty, generation, card)
self.assertTrue(all(row['average'] is None and row['samples'] == 0 for row in rows))
if __name__ == '__main__':
unittest.main()

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