From 5db8661a1aff965ca1e2f36c7c28f026923bffd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 25 Nov 2026 09:46:26 -0300 Subject: [PATCH] fix: the Kanban says the proof machine before a pull, folder downloads cut by the network wait for the next pass, expected refusals stay out of Sentry (DTF-WEB-16..1K, DTF-API-C) - 19/1F: the board carries the approved proof's machine; the pull and the order's machine field keep to it and say why. - 17/1E: a network drop while a download or an answer arrives counts as unreachable/offline, warned first like the others. - 16: no folder picker (Safari): said in a line. - 1A, 1J/1K, 1D, 18: guidance and expected refusals (pull to another machine, someone already on the machine, e-mail in use, coupon) are not errors. - 1B: an empty file is refused on the page. - API-C: the Tiny's rate limit reaches Sentry only if it repeats. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/api/operator/board.py | 6 ++++-- app/tiny.py | 8 +++++++- app/worker.py | 5 +++-- tests/test_worker_drain.py | 10 ++++++++-- web/checkout.js | 12 ++++++++---- web/kanban-users.js | 26 ++++++++++++++++++++++---- web/kanban.js | 19 +++++++++++++++---- web/site-upload.js | 10 ++++++++++ 8 files changed, 77 insertions(+), 19 deletions(-) diff --git a/app/api/operator/board.py b/app/api/operator/board.py index 6db1bbc..4e40eb0 100644 --- a/app/api/operator/board.py +++ b/app/api/operator/board.py @@ -211,7 +211,7 @@ def with_print_files(c, orders): hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp']) # Each parent's latest proof card, and each card's parent (app/proof.py). children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state, - proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders + proof_result,proof_decided_at,proof_decided_by,proof_reason,machine_id FROM dtf_local.orders WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()} parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)', ([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()} @@ -225,8 +225,10 @@ def with_print_files(c, orders): order['hot'] = hot.get(order['id']) order['reviews'] = review_rows.get(str(order['id']), []) child = children.get(order['id']) + # Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05). order['proof_card'] = child and {**{k: child[k] for k in ('id', 'number', 'state', 'proof_result', - 'proof_decided_at', 'proof_decided_by', 'proof_reason')}, + 'proof_decided_at', 'proof_decided_by', 'proof_reason', + 'machine_id')}, 'reviews': proof_reviews.get(str(child['id']), [])} parent = parents.get(order.get('parent_id')) order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']} diff --git a/app/tiny.py b/app/tiny.py index 3ce5d97..c5ce929 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -188,6 +188,12 @@ class TinyError(Exception): pass +class TinyRateLimit(TinyError): + """Too many calls for the moment: the outbox's next try goes through + (Sentry DTF-API-C). `transient`: the worker reports it only if it repeats.""" + transient = True + + class TinyNotConnected(TinyError): """No authorised connection yet: an operator must click "Conectar Tiny".""" @@ -812,7 +818,7 @@ class TinyOrders: headers = {'Authorization': f'Bearer {self.auth.access_token()}'} response = self.http.request(method, path, headers=headers, **kwargs) if response.status_code == 429: - raise TinyError('Tiny rate limit reached; the outbox will retry') + raise TinyRateLimit('Tiny rate limit reached; the outbox will retry') if response.status_code >= 400: raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') return response.json() if response.content else {} diff --git a/app/worker.py b/app/worker.py index 277d3bc..189fbaf 100644 --- a/app/worker.py +++ b/app/worker.py @@ -81,9 +81,10 @@ def tick(): # Sentry hears of a refused delivery on its first failure and # every tenth after, not only Integrações (the Tiny refused # #42 fourteen times unseen, 2026-11-18). One message - # template, so Sentry keeps it as one issue per kind. + # template, so Sentry keeps it as one issue per kind. A + # passing refusal (the Tiny's rate limit) only from the tenth. attempt = job['attempts'] + 1 - if attempt == 1 or attempt % 10 == 0: + if attempt == 1 and not getattr(exc, 'transient', False) or attempt % 10 == 0: logging.error('Outbox delivery to %s failed (%s, attempt %s): %s', job['provider'], job['event_key'], attempt, str(exc)[:500]) last_tick = time.monotonic() diff --git a/tests/test_worker_drain.py b/tests/test_worker_drain.py index a66bcc4..98329d2 100644 --- a/tests/test_worker_drain.py +++ b/tests/test_worker_drain.py @@ -27,14 +27,14 @@ class WorkerDrainTest(unittest.TestCase): class RefusedDeliveryTest(unittest.TestCase): """A delivery the provider refuses reaches Sentry (logging.error) on its first failure and every tenth after (#42, 2026-11-18).""" - def tick_with(self, attempts): + def tick_with(self, attempts, refusal=None): job = {'id': 1, 'provider': 'tiny', 'event_key': 'o:paid:tiny', 'payload': {}, 'attempts': attempts} conn = mock.MagicMock() conn.execute.return_value.fetchone.return_value = job connect = mock.MagicMock() connect.return_value.__enter__.return_value = conn refusing = mock.MagicMock() - refusing.deliver.side_effect = RuntimeError('Forma de recebimento não está habilitada') + refusing.deliver.side_effect = refusal or RuntimeError('Forma de recebimento não está habilitada') with mock.patch.object(worker, 'connect', connect), \ mock.patch.dict(worker.adapters, {'tiny': refusing}), \ mock.patch.object(worker.logging, 'error') as error: @@ -46,6 +46,12 @@ class RefusedDeliveryTest(unittest.TestCase): self.assertEqual(self.tick_with(9).call_count, 1) self.assertEqual(self.tick_with(4).call_count, 0) + def test_a_rate_limit_is_reported_only_when_it_repeats(self): + from app.tiny import TinyRateLimit + limit = TinyRateLimit('Tiny rate limit reached; the outbox will retry') + self.assertEqual(self.tick_with(0, limit).call_count, 0) + self.assertEqual(self.tick_with(9, limit).call_count, 1) + if __name__ == '__main__': unittest.main() diff --git a/web/checkout.js b/web/checkout.js index d100a3f..f24621a 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -56,8 +56,9 @@ const retry=response.headers.get('Retry-After'); if(retry!=null)error.retryAfter=retry; // A status the caller expects (a resumed upload that expired) is handled - // there, not reported. - if(!(options.expected||[]).includes(response.status)) + // there, not reported. `expected` may also be a test of status and text. + const expected=options.expected; + if(!(typeof expected==='function'?expected(response.status,error.message):(expected||[]).includes(response.status))) window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); throw error; } @@ -152,6 +153,9 @@ // One message line under the steps. Its tone says what it is: a refusal or // a missing field is an error (red), a cart that changed a warning, a // created order a confirmation, the rest information. + // A code the customer typed wrong, or one no longer valid (app/coupons.py): + // they fix it, it is no error (Sentry DTF-WEB-18). + const couponRefusal=(status,text)=>status===422&&/^(Cupom |Este cupom |Você já usou este cupom)/.test(text||''); function message(text, tone='info') { status.textContent = text; status.dataset.tone = text ? tone : ''; if (tone === 'error' && text) window.dtfObservability?.uiError?.(text, 'site'); @@ -553,11 +557,11 @@ localStorage.setItem('dtf-request-key',requestKey); localStorage.setItem('dtf-request-body',requestBody); } - const quote = await api('/quotes',{request_key:requestKey,...content,timings}); + const quote = await api('/quotes',{request_key:requestKey,...content,timings},{expected:couponRefusal}); quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart); draftId=quote.id; localStorage.setItem('dtf-quote',draftId); await refresh(true); - } catch(error) { message(error.message,'error'); } + } catch(error) { message(error.message,couponRefusal(error.status,error.message)?'warn':'error'); } finally { busy=false; pintaEntrega(); } }; // `go`: the customer asked to pay, so the cart page moves to the payment page. diff --git a/web/kanban-users.js b/web/kanban-users.js index 171b9c6..0737df3 100644 --- a/web/kanban-users.js +++ b/web/kanban-users.js @@ -36,7 +36,8 @@ function askMachine(again=false){ const required=ME.machine_question==='required', current=myMachine(); let m=null; const choose=async(id,confirm=false)=>{ - try{await api('/me/machine',{machine_id:id,confirm});m.close();await load(true);} + // Someone else on the machine is a question, not an error (Sentry DTF-WEB-1J). + try{await api('/me/machine',{machine_id:id,confirm},{expected:confirm?[]:[409]});m.close();await load(true);} catch(e){ if(e.status===409&&!confirm&&await ask('Outra pessoa está nesta máquina',e.message,'Continuar mesmo assim'))return choose(id,true); say(e.message,true);}}; @@ -69,6 +70,12 @@ function paintMyMachine(){ for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true); $('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);}; +// The machine that printed the order's approved proof: the order prints +// there too, and the server refuses any other (Sentry DTF-WEB-19, 1F). +function proofMachine(order){ + const card=order.proof_card; + return card?.proof_result==='ok'&&card.machine_id?(board.machines||[]).find(m=>m.id===card.machine_id)||{id:card.machine_id,name:'máquina da prova'}:null; +} // The machine is recorded when the card is pulled into Imprimindo. function machineCard(order){ const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl')); @@ -80,6 +87,11 @@ function machineCard(order){ box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail)); return box; } + const proofAt=proofMachine(order); + if(proofAt){ + box.append(node('b',proofAt.name),node('span','A máquina que imprimiu a prova #'+order.proof_card.number)); + return box; + } const select=node('select');select.setAttribute('aria-label','Máquina do pedido'); const auto=node('option','Sem máquina');auto.value='';select.append(auto); const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil'; @@ -273,7 +285,8 @@ function userForm(u){ label:editing?'Salvar':'Criar usuário',onsave:async()=>{ const picked=seller.value?{id:Number(seller.value),name:seller.selectedOptions[0].textContent.replace(/ \(não está mais no Tiny\)$/,'')}:null; const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null,tiny_seller:picked}; - await api(editing?'/users/'+u.id:'/users',body); + // An e-mail already in use is said in the form, not an error (Sentry DTF-WEB-1D). + await api(editing?'/users/'+u.id:'/users',body,{expected:[409]}); say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers(); }}); } @@ -647,17 +660,22 @@ async function pullTo(order, machineId){ if(ME?.role==='operador'){ const mine=myMachine(); if(!mine){askMachine(true);return;} + // Guidance, not an error: the pull goes to the session's machine (Sentry DTF-WEB-1A). if(machineId&&machineId!==mine.id){ - say('Você está na '+mine.name+': o que você puxa vai para ela.',true);return; + say('Você está na '+mine.name+': o que você puxa vai para ela.');return; } target=mine.id; }else{ - target=machineId||order.machine?.id||myMachine()?.id||null; + target=machineId||proofMachine(order)?.id||order.machine?.id||myMachine()?.id||null; if(!target){ target=await choosePullMachine(order); if(!target)return; } } + const proofAt=proofMachine(order); + if(proofAt&&target!==proofAt.id){ + say('O #'+order.number+' imprime na '+proofAt.name+', a máquina que imprimiu a prova #'+order.proof_card.number+'.');return; + } const machine=(board.machines||[]).find(row=>row.id===target); // A lane drop, or a machine chosen before, may be one that does not print // this product (by its first item, as app/machines.py product_family): said diff --git a/web/kanban.js b/web/kanban.js index db4d07d..19d7402 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -228,12 +228,14 @@ function freightWeight(fr){ } // A download button: the arrow, then its label. function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(svgIcon(IC.download,'i m'));return b;} -async function api(path,body){ +async function api(path,body,options={}){ // A fetch that never reached the server (no network) is marked offline. let r; try{r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});} catch(e){e.offline=true;throw e;} - const d=await r.json(); + // The network can also drop while the answer arrives (Sentry DTF-WEB-1E). + let d; + try{d=await r.json();}catch(e){if(e instanceof TypeError)e.offline=true;throw e;} if(!r.ok){ // A validation error is a list: name its first field and what was wrong // instead of the bare status (Sentry DTF-WEB-E). @@ -242,7 +244,8 @@ async function api(path,body){ const error=new Error(typeof d.detail==='string'?d.detail: 'Confira os campos ('+r.status+')'+(first?': '+(field?field+', ':'')+first.msg:'.')); error.status=r.status; - window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail); + // A status the caller expects and answers itself is not reported. + if(!(options.expected||[]).includes(r.status))window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail); throw error; } return d; @@ -403,6 +406,8 @@ function paintFolder(){ $('badge-integrations').textContent=attention?'!':''; } async function chooseFolder(){ + // Safari and the phones have no folder picker (Sentry DTF-WEB-16). + if(!('showDirectoryPicker' in window)){say('Este navegador não grava em pastas. Use o Chrome ou o Edge no computador da fábrica.');return;} let handle; try{handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'});} catch(e){if(e.name==='AbortError')return;throw e;} @@ -461,7 +466,13 @@ async function writeWhole(dir,name,source,watched=false){ try{ const out=await temp.createWritable(); try{if(blob){await out.write(source);await out.close();}else await source.body.pipeTo(out);} - catch(e){await out.abort().catch(()=>{});throw e;} + catch(e){ + await out.abort().catch(()=>{}); + // A download the network cut halfway waits for the next pass, as one + // that never started (Sentry DTF-WEB-17). + if(!blob&&e instanceof TypeError)e.unreachable=true; + throw e; + } const size=(await temp.getFile()).size; if(!size||expected&&size!==expected) throw new IncompleteFile('O arquivo '+name+' chegou incompleto ('+fileSize(size)+(expected?' de '+fileSize(expected):'')+') e foi descartado.'); diff --git a/web/site-upload.js b/web/site-upload.js index d60d71f..4e86f6c 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -174,6 +174,16 @@ async function sel(fs){ ' GB. Divida a folha em partes menores antes de enviar.'; fs=fs.filter(f=>f.size<=max); } + // A file of 0 bytes (a copy that failed, a cloud placeholder): said here, + // never sent (Sentry DTF-WEB-1B). + const vazios=fs.filter(f=>!f.size); + if(vazios.length){ + const el=$('recusa'); + el.style.display='block'; + el.innerHTML=''+escapeHTML(vazios.map(f=>f.name).join(', '))+(vazios.length>1?' estão vazios':' está vazio')+ + ' (0 bytes). Abra o arquivo no seu computador para conferir e escolha de novo.'; + fs=fs.filter(f=>f.size); + } if(!fs.length) return; // On their way at once; a JPG is refused at the order anyway. fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));