From 6351a094f4d03b9e2edef3d1c5cfbb1d9706ce86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 6 Nov 2026 11:09:36 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20N=C3=BAmeros=20measures=20the=20site=20?= =?UTF-8?q?and=20the=20Prumo=20(0.12)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- app/api/operator.py | 67 +++++++++++++++++++++++++++++++++++++++++++++ app/core/models.py | 15 ++++++++++ app/quote_review.py | 2 ++ tests/test_speed.py | 35 +++++++++++++++++++++++ web/checkout.js | 20 ++++++++++++-- web/kanban.html | 2 ++ web/kanban.js | 11 ++++++++ web/site-config.js | 6 ++++ web/site-packing.js | 2 ++ web/site-quality.js | 9 ++++++ web/site-upload.js | 4 +++ 11 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 tests/test_speed.py diff --git a/app/api/operator.py b/app/api/operator.py index 9db07a4..68eb8ac 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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.""" diff --git a/app/core/models.py b/app/core/models.py index db0c9ac..286141d 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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): diff --git a/app/quote_review.py b/app/quote_review.py index 1b45c5a..b1192c1 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -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'])) diff --git a/tests/test_speed.py b/tests/test_speed.py new file mode 100644 index 0000000..fe354b2 --- /dev/null +++ b/tests/test_speed.py @@ -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() diff --git a/web/checkout.js b/web/checkout.js index eccb3c3..d631d8f 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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); diff --git a/web/kanban.html b/web/kanban.html index 4e21f74..85e707f 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -142,6 +142,8 @@

Tempo em cada etapa

EtapaMedianaAgora
+

Velocidade do site e do Prumo

+
EtapaMédiap95Amostras