fix: large carts upload all their files (Marcus's bugs of 11/11, B1 to B4)
B1: an upload start was limited to 60 per 15 minutes per session, so a 66-file cart failed with 'Muitas tentativas'; now 1000 per session and 3000 per source, and the Site waits Retry-After and retries quietly. B2: a failed file shows its error and 'Tentar de novo' on its own card, and payment stays blocked with 'Falta enviar N arquivos'. B3: after signing in again, an upload id the new session does not own (403) is dropped and the file starts again. B4: the quote is never created before every file is sent, and an untranslatable 422 is logged for Sentry. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -46,7 +46,17 @@
|
||||
let data;
|
||||
try { data = text ? JSON.parse(text) : {}; }
|
||||
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
|
||||
if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; }
|
||||
if (!response.ok) {
|
||||
const text=problem(data.detail);
|
||||
// A validation the customer cannot read still needs to reach us (Sentry
|
||||
// picks up console.error later); the customer keeps the generic sentence.
|
||||
if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.')
|
||||
console.error('Detalhe da validação recusada:',data.detail);
|
||||
const error=new Error(text);error.status=response.status;
|
||||
const retry=response.headers.get('Retry-After');
|
||||
if(retry!=null)error.retryAfter=retry;
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
// A refusal as one sentence: the server's own, or the first field a form
|
||||
@@ -262,10 +272,35 @@
|
||||
pintaEnvio();
|
||||
}
|
||||
const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
|
||||
// Every file of the paying cart must be sent (and none failed) before the
|
||||
// quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11).
|
||||
function faltaEnvio(){
|
||||
const files=arquivosDoCarrinho();
|
||||
let pending=0,failed=0;
|
||||
for(const f of files){
|
||||
const k=chaveArquivo(f);
|
||||
if(falhas.has(k)){failed++;continue;}
|
||||
const e=envios.get(k);
|
||||
if(!e||!e.done)pending++;
|
||||
}
|
||||
return {total:files.length,pending,failed,falta:pending+failed};
|
||||
}
|
||||
window.dtfFaltaEnvio=faltaEnvio;
|
||||
function faltaEnvioMensagem(){
|
||||
const missing=[];
|
||||
for(const f of arquivosDoCarrinho()){
|
||||
const k=chaveArquivo(f),e=envios.get(k);
|
||||
if(falhas.has(k)||!e||!e.done)missing.push(f);
|
||||
}
|
||||
if(!missing.length) return '';
|
||||
return 'Falta enviar '+missing[0].name+
|
||||
(missing.length>1?' (e mais '+(missing.length-1)+')':'');
|
||||
}
|
||||
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
|
||||
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
|
||||
// Where the uploads stand, and roughly how long is left from the recent speed.
|
||||
const amostras=[];
|
||||
let ultimaFalta=null;
|
||||
function estadoEnvio() {
|
||||
const files=arquivosDoCarrinho(); if(!files.length) return null;
|
||||
let total=0, sent=0, pendentes=0;
|
||||
@@ -292,6 +327,13 @@
|
||||
return 'Enviando seus arquivos · '+restante(e);
|
||||
}
|
||||
function pintaEnvio() {
|
||||
// The cart button carries the uploads too (B2): repaint it only when the
|
||||
// number of missing files changes, not on every progress tick.
|
||||
const falta=faltaEnvio().falta;
|
||||
if(falta!==ultimaFalta){
|
||||
ultimaFalta=falta;
|
||||
if(typeof pintaPedido==='function')pintaPedido();
|
||||
}
|
||||
window.dispatchEvent(new Event('dtf-envio'));
|
||||
const e=estadoEnvio(), texto=textoEnvio(e);
|
||||
const el=document.getElementById('envioArq');
|
||||
@@ -391,6 +433,8 @@
|
||||
if (!clienteOk() || !entrega.cotado) return;
|
||||
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
|
||||
if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error');
|
||||
const semArquivo=faltaEnvioMensagem();
|
||||
if (semArquivo) return message(semArquivo+'.','error');
|
||||
const cart = itensAPagar();
|
||||
if (!cart.length) return message('Adicione um item ao pedido.','error');
|
||||
const initialCart=cartSnapshot();
|
||||
|
||||
@@ -114,13 +114,18 @@ function pintaPedido(){
|
||||
'<div class="l"><span>Revisão e reencaixe</span>'+
|
||||
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
||||
$('carrTot').textContent=rs(soma);
|
||||
$('bPagarTx').textContent = n>1
|
||||
? 'Pagar os '+n+' itens de uma vez'
|
||||
: 'Ir para o pagamento';
|
||||
// A file still on its way (or failed) keeps the payment closed (B2).
|
||||
const faltaEnvio=window.dtfFaltaEnvio?window.dtfFaltaEnvio():null;
|
||||
const falta=faltaEnvio?.falta||0;
|
||||
$('bPagarTx').textContent = falta
|
||||
? 'Falta enviar '+falta+(falta===1?' arquivo':' arquivos')
|
||||
: n>1
|
||||
? 'Pagar os '+n+' itens de uma vez'
|
||||
: 'Ir para o pagamento';
|
||||
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
|
||||
const prova=$('fProva');
|
||||
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
|
||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk();
|
||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
|
||||
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
||||
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
||||
$('cartLink').setAttribute('aria-label','Carrinho, '+noCarrinho+(noCarrinho===1?' item':' itens')); }
|
||||
|
||||
@@ -66,9 +66,44 @@ const enviadoEm=new WeakMap();
|
||||
// A few repaints a second, page in view or not: progress comes in far more often.
|
||||
let envioQuadro=0;
|
||||
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
|
||||
// A failed upload must show on the file's own card too (B2, Marcus 11/11):
|
||||
// the same red block and "Tentar de novo" as the row under the uploader, on
|
||||
// the sheet/art card itself, so the list does not look complete.
|
||||
function pintaErrosDosArquivos(){
|
||||
const lista=$('lista'); if(!lista || !window.dtfEnvio) return;
|
||||
const decorate=(selector,items,kind)=>{
|
||||
items.forEach((item,index)=>{
|
||||
const card=lista.querySelector(selector.replace('{i}',index));
|
||||
if(!card) return;
|
||||
const estado=dtfEnvio.estado(item.f);
|
||||
const atual=card.querySelector('[data-envio-falha]');
|
||||
if(!estado || estado.fase!=='falhou'){ if(atual) atual.remove(); return; }
|
||||
if(atual){
|
||||
// Keep the block while the file is failed: a repaint for another
|
||||
// file's progress must not take the button from under the pointer.
|
||||
const texto=atual.querySelector('span');
|
||||
if(texto) texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||
return;
|
||||
}
|
||||
const box=document.createElement('div');
|
||||
box.className='envio erro';box.dataset.envioFalha='1';
|
||||
const texto=document.createElement('span');
|
||||
texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||
const button=document.createElement('button');
|
||||
button.type='button';button.textContent='Tentar de novo';
|
||||
button.dataset.envioCard=kind;button.dataset.envioIndex=String(index);
|
||||
box.append(texto,button);card.append(box);
|
||||
});
|
||||
};
|
||||
decorate('[data-folha="{i}"]',folhas,'folha');
|
||||
decorate('[data-arte="{i}"]',artes,'arte');
|
||||
}
|
||||
function pintaEnvios(){
|
||||
const el=$('envios'); if(!el || !window.dtfEnvio) return;
|
||||
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
|
||||
pintaErrosDosArquivos();
|
||||
// Off the product page there is no uploader to paint under.
|
||||
if(!MODOS[modo]){ el.innerHTML=''; return; }
|
||||
const agora=Date.now();
|
||||
@@ -92,6 +127,11 @@ $('envios').addEventListener('click',e=>{
|
||||
const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return;
|
||||
const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f);
|
||||
});
|
||||
$('lista').addEventListener('click',e=>{
|
||||
const b=e.target.closest('[data-envio-card]'); if(!b || !window.dtfEnvio) return;
|
||||
const x=(b.dataset.envioCard==='folha'?folhas:artes)[+b.dataset.envioIndex];
|
||||
if(x) dtfEnvio.deNovo(x.f);
|
||||
});
|
||||
// A sheet with residue gets its preview circled where the dots are.
|
||||
async function marcaResiduos(x){
|
||||
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
|
||||
|
||||
@@ -4,9 +4,36 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]);
|
||||
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join('');
|
||||
const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]);
|
||||
// A busy server asks for a wait: retry this file alone, quietly, before the
|
||||
// customer sees the failure (Marcus, 2026-11-11). Only a 429 that carries
|
||||
// Retry-After; the quota refusal has none and is shown at once.
|
||||
const retryWait=error=>{
|
||||
const seconds=Number(error?.retryAfter);
|
||||
return error?.status===429&&Number.isFinite(seconds)?Math.min(60,Math.max(1,Math.ceil(seconds))):null;
|
||||
};
|
||||
const withRetry=async call=>{
|
||||
for(let attempt=0;;attempt++){
|
||||
try{return await call();}
|
||||
catch(error){
|
||||
const wait=retryWait(error);
|
||||
if(wait===null||attempt>=3)throw error;
|
||||
await new Promise(resolve=>setTimeout(resolve,wait*1000));
|
||||
}
|
||||
}
|
||||
};
|
||||
let id=resume?localStorage.getItem(key):null,state;
|
||||
if(id){try{state=await api(prefix+'/'+id);}catch(error){if(![404,410].includes(error.status))throw error;id=null;}}
|
||||
if(!id){state=await api(startPath,{name:file.name,size:file.size});id=state.id;if(resume)localStorage.setItem(key,id);}
|
||||
if(id){
|
||||
try{state=await api(prefix+'/'+id);}
|
||||
catch(error){
|
||||
// The id was started under another session (a sign-in changes the scope):
|
||||
// the new session does not own it, so this file starts again as a new
|
||||
// upload. A 403/404/410 must never keep the retry on the old id.
|
||||
if(![403,404,410].includes(error.status))throw error;
|
||||
id=null;
|
||||
if(resume)localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
if(!id){state=await withRetry(()=>api(startPath,{name:file.name,size:file.size}));id=state.id;if(resume)localStorage.setItem(key,id);}
|
||||
async function waitForScan(){
|
||||
onBytes(file.size);
|
||||
// The antivirus streams the whole file: about a second per 2 MB, and at
|
||||
@@ -42,7 +69,7 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
if(done.has(part))continue;
|
||||
if(signal?.aborted)throw cancelled();
|
||||
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
|
||||
const signed=await api(prefix+'/'+id+'/parts/'+part,{});
|
||||
const signed=await withRetry(()=>api(prefix+'/'+id+'/parts/'+part,{}));
|
||||
await put(signed.url,file.slice(offset,offset+size));
|
||||
done.add(part);sent+=length(part);
|
||||
onBytes(sent);
|
||||
|
||||
Reference in New Issue
Block a user