From 3428ff68be21db4f2bc0ce52c220c5cd5c172c85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 30 Nov 2026 16:09:52 -0300 Subject: [PATCH] feat: Minhas folhas on the Site: save a cart item to the account, order it again with the files already on the server, edit it without sending them again (Rodada 5, B9) Co-Authored-By: Claude Opus 5.5 --- web/cart.js | 4 +++ web/checkout.js | 39 +++++++++++++++++++----- web/site-cart.js | 40 +++++++++++++++++++++++++ web/site-upload.js | 74 ++++++++++++++++++++++++++++++++++++++++++++++ web/site-v2.css | 7 +++++ 5 files changed, 156 insertions(+), 8 deletions(-) diff --git a/web/cart.js b/web/cart.js index a647e40..8f5e20e 100644 --- a/web/cart.js +++ b/web/cart.js @@ -43,6 +43,7 @@ // A signed-in customer's details come from the account, with the saved // delivery address, whether or not a cart was recovered. const account=await window.dtfApi('/account/me'); + window.dtfContaAberta=!!account.customer; const c=account.customer; if(c && !cliente.mail){ cliente={name:c.name||'',cnpj:c.cnpj,zap:c.zap,mail:c.mail}; @@ -57,6 +58,9 @@ } pintaEntrega(); } + // The account's save button only exists after this answer. + window.dispatchEvent(new Event('dtf-cart-changed')); + if(typeof pintaPedido==='function') pintaPedido(); }catch(error){notice.textContent='Recuperação de carrinho indisponível; o pedido ainda pode ser feito nesta sessão.';} finally{restoring=false;} })(); diff --git a/web/checkout.js b/web/checkout.js index 37a333e..ba160e5 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -26,7 +26,8 @@ residue:item.residueAccepted||0, stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null, sheets:(item.partes||[]).map(part=>part.production), - files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified})) + files:[...(item.localFiles||[]),...(item.savedFiles||[])] + .map(file=>({name:file.name,size:file.size,lastModified:file.lastModified})) })),treatment:ajusteSnapshot(),coupon:cupomCode()}); } // The quote this browser is paying, forgotten. clearDraft also empties the @@ -149,6 +150,7 @@ }).catch(()=>{}); window.dtfSessionReady=ready; window.dtfApi=api; + window.dtfMensagem=message; ready.catch(error => { status.textContent = error.message; }); // 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 @@ -269,7 +271,9 @@ } } })(); - e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();}, + e.promise.then(id=>{e.id=id;e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio(); + // "Salvar em Minhas folhas" waits for the item's files: the cart repaints when one lands. + if(window.dtfContaAberta&&typeof pintaPedido==='function')pintaPedido();}, error=>{envios.delete(k);if(error?.name!=='AbortError'){falhas.set(k,{file,error}); // A refusal with a status already went to Sentry as an API error (DTF-WEB-15). if(!error?.status)window.dtfObservability?.uiError?.('Envio de arquivo falhou: '+(error?.message||'erro no envio'),'site');}pintaEnvio();}); @@ -279,11 +283,23 @@ } // Each file's upload as the product page shows it, under the uploader. window.dtfEnvio={ - enviar:file=>{if(!falhas.has(chaveArquivo(file)))enviar(file).catch(()=>{});}, + enviar:file=>{ + if(falhas.has(chaveArquivo(file)))return Promise.resolve(null); + const p=enviar(file); p.catch(()=>{}); return p; + }, estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k); return f?{fase:'falhou',erro:f.error?.message||'erro no envio'} :!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};}, deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();}, + // A file already on the server (a saved sheet opened for editing): its id + // is known, so a later enviar(file) resolves at once and sends nothing. + conhecido:(file,uploadId)=>{ + const k=chaveArquivo(file); + falhas.delete(k); + envios.set(k,{file,sent:file.size,done:true,id:uploadId,failed:null, + stop:new AbortController(),promise:Promise.resolve(uploadId)}); + }, + idDe:file=>{const e=envios.get(chaveArquivo(file));return e&&e.done?(e.id??null):null;}, // A file taken off the page, and in no cart item, stops going. manter:files=>{ const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo)); @@ -495,7 +511,8 @@ // One item carries at most 200 files (app/core/models.py); a bigger cart // line is refused here, with the reason, never by the generic 422. const semCap=cart.flatMap(line=>line.partes?.length?line.partes:[line]); - if (semCap.some(item=>(item.localFiles||[]).length>200)) + const totalArquivos=item=>(item.localFiles||[]).length+(item.savedFiles||[]).length; + if (semCap.some(item=>totalArquivos(item)>200)) return message('Este item tem mais de 200 arquivos. Divida em dois itens.','error'); const initialCart=cartSnapshot(); busy = true; @@ -511,11 +528,17 @@ ? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}})) : [line]); for (const item of sheets) { - if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.'); + const locais=item.localFiles||[], salvos=item.savedFiles||[]; + if (!locais.length && !salvos.length) throw new Error('Selecione novamente os arquivos deste item.'); const uploads=[]; - for (const [index,file] of item.localFiles.entries()) { - uploads.push(await upload(file)); - enviaFoto(uploads[index], item.fotos?.[index]); + if (salvos.length) { + // A sheet kept in Minhas folhas: the server already has the files. + for (const saved of salvos) uploads.push(saved.upload_id); + } else { + for (const [index,file] of locais.entries()) { + uploads.push(await upload(file)); + enviaFoto(uploads[index], item.fotos?.[index]); + } } // Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before. if (![2,3].includes(item.production?.version) || item.production.sources?.length!==uploads.length) diff --git a/web/site-cart.js b/web/site-cart.js index 44b181c..46618c8 100644 --- a/web/site-cart.js +++ b/web/site-cart.js @@ -190,6 +190,29 @@ function aplicaTratamento(aPagar){ check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento(''); } } +// Minhas folhas: the files of an item, and whether they are all already on +// the server (or the item came back from Minhas folhas with its own ids). +function arquivosDoItem(it){ + return [...(it.localFiles||[]),...(it.partes||[]).flatMap(p=>p.localFiles||[])]; +} +function podeSalvarFolha(it){ + if((it.savedFiles||[]).length || (it.partes||[]).some(p=>(p.savedFiles||[]).length)) return true; + return arquivosDoItem(it).every(f=>!!window.dtfEnvio?.idDe(f)); +} +// The cart item as Minhas folhas keeps it: files become their upload ids, +// without the pictures and without the cart's own marks. +function itemParaSalvar(it){ + const copia=JSON.parse(JSON.stringify(it)); + const pares=[{orig:it,dest:copia}]; + (it.partes||[]).forEach((p,i)=>pares.push({orig:p,dest:copia.partes[i]})); + for(const {orig,dest} of pares){ + dest.savedFiles=(orig.savedFiles||[]).length ? orig.savedFiles : (orig.localFiles||[]).map(f=>({ + upload_id:window.dtfEnvio?.idDe(f),name:f.name,size:f.size,lastModified:f.lastModified,type:f.type + })); + delete dest.localFiles; delete dest.fotos; delete dest.marcado; + } + return copia; +} // O carrinho junta itens de produtos diferentes e cobra uma vez só. function pintaPedido(){ const aPagar = itensAPagar(); @@ -221,6 +244,9 @@ function pintaPedido(){ '
'+escapeHTML(it.tit)+''+escapeHTML(it.desc)+''+ (semMargem(it)?'O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.':'')+'
'+ '
'+rs(it.total)+'
'+ + (window.dtfContaAberta?'':'')+ '').join(''); $('itens').querySelectorAll('[data-sel]').forEach(c=>c.addEventListener('change',()=>{ pedido[+c.dataset.sel].marcado=c.checked; pintaPedido(); @@ -232,6 +258,20 @@ function pintaPedido(){ pedido.splice(Math.min(i,pedido.length),0,item); pintaPedido(); }); })); + $('itens').querySelectorAll('[data-salvai]').forEach(b=>b.addEventListener('click',async()=>{ + const it=pedido[+b.dataset.salvai]; if(!it || b.disabled) return; + const picture=typeof it.mini==='string' && /^data:/.test(it.mini) && it.mini.length<=300000 ? it.mini : null; + b.disabled=true; + try{ + await window.dtfApi('/account/sheets',{name:it.tit+' · '+fmtM(it.cob)+' m',mode:it.modo, + metres:it.cob,item:itemParaSalvar(it),picture}); + window.dtfMensagem?.('Folha salva em Minhas folhas.','ok'); + }catch(error){ + window.dtfMensagem?.(error.message,'error'); + }finally{ + b.disabled=!podeSalvarFolha(it); + } + })); $('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2; const itens = aPagar.reduce((t,it)=>t+it.total,0); const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0; diff --git a/web/site-upload.js b/web/site-upload.js index b6207c7..bc7fa1d 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -364,3 +364,77 @@ function tracoDaArte(a){ // imagem → proporção da imagem aplicada à largura do filme // PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit // TIFF, PSD, AI, CDR → o navegador não abre; o cliente informa o comprimento + +// Minhas folhas: "Editar" opens the product with ?folha=. The files come +// from the server, so nothing is sent again, and the saved measures go back +// onto the new cards. +const folhaSalvaId=new URLSearchParams(location.search).get('folha'); +let folhaSalvaAberta=false; +function mensagemFolhaSalva(texto){ + const el=$('aoVivo'); + if(el){el.className='aoVivo'; el.textContent=texto;} +} +function seguraMensagemFolhaSalva(){ + // The live check repaints aoVivo a moment after opening; while the saved + // sheet comes, that line belongs to the loading message. + try{ if(tAval){clearTimeout(tAval);tAval=null;} }catch(_){} + mensagemFolhaSalva('Abrindo a folha salva…'); +} +async function abrirFolhaSalva(id){ + seguraMensagemFolhaSalva(); + try{ + const {sheets}=await window.dtfApi('/account/sheets'); + const folha=(sheets||[]).find(s=>String(s.id)===String(id)); + if(!folha){ mensagemFolhaSalva('Folha não encontrada.'); return; } + seguraMensagemFolhaSalva(); + const {files}=await window.dtfApi('/account/sheets/'+encodeURIComponent(id)+'/files',{}); + const item=folha.item||{}; + const guardadas=item.partes?.length + ? item.partes.flatMap(p=>p.savedFiles||[]) + : (item.savedFiles||[]); + const fontes=item.partes?.length + ? item.partes.flatMap(p=>p.production?.sources||[]) + : (item.production?.sources||[]); + const porId=new Map((files||[]).map(f=>[f.upload_id,f])); + const lista=guardadas.length + ? guardadas.map(meta=>({meta,arquivo:porId.get(meta.upload_id)})).filter(x=>x.arquivo) + : (files||[]).map(arquivo=>({meta:null,arquivo})); + const baixados=[]; + seguraMensagemFolhaSalva(); + for(const {meta,arquivo} of lista){ + const resposta=await fetch(arquivo.url); + if(!resposta.ok) throw new Error('download'); + const blob=await resposta.blob(); + const file=new File([blob],meta?.name||arquivo.name||'arquivo', + {type:meta?.type||blob.type||'',lastModified:meta?.lastModified||Date.now()}); + window.dtfEnvio?.conhecido(file,arquivo.upload_id); + baixados.push(file); + } + if(!baixados.length) throw new Error('download'); + const antesArtes=artes.length, antesFolhas=folhas.length; + await sel(baixados); + if(ehFolha()){ + const novas=folhas.slice(antesFolhas); + novas.forEach((x,i)=>{const fonte=fontes[i]; if(fonte) x.rep=fonte.copies||1;}); + pintaFolha(); + }else{ + const novas=artes.slice(0,Math.max(0,artes.length-antesArtes)); + novas.forEach((a,i)=>{const fonte=fontes[i]; if(fonte){ + a.cm=fonte.width_cm; a.q=fonte.copies; + a.giro=fonte.rotation_degrees?90:0; a.esp=!!fonte.mirrored; + }}); + pintaArtes(); + } + const url=new URL(location.href); url.searchParams.delete('folha'); + history.replaceState(history.state,'',url.pathname+url.search+url.hash); + }catch(error){ + mensagemFolhaSalva(error?.status===409 + ? error.message : 'Não foi possível abrir a folha salva. Tente de novo.'); + } +} +addEventListener('dtf-page-changed',()=>{ + if(folhaSalvaAberta || !folhaSalvaId || !modo || + document.documentElement.dataset.rota!=='produto') return; + folhaSalvaAberta=true; + abrirFolhaSalva(folhaSalvaId); +}); diff --git a/web/site-v2.css b/web/site-v2.css index f892409..c6f67ed 100644 --- a/web/site-v2.css +++ b/web/site-v2.css @@ -586,3 +586,10 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te #vArea .folhasTraco{display:flex;flex-direction:column;gap:14px} #vArea .folhaTraco{margin:0;display:flex;flex-direction:column;gap:6px} #vArea .folhaTraco figcaption{font-size:14.5px;font-weight:700;color:var(--texto2)} + +/* Minhas folhas: saving a cart item to the account. */ +.salvaBt{flex:none;height:36px;padding:0 12px;border-radius:var(--raio2);border:1px solid var(--linha);background:#fff;color:var(--texto2);font-family:inherit;font-size:14px;font-weight:600;cursor:pointer} +.salvaBt:hover:not(:disabled){border-color:var(--laranja);color:var(--preto)} +.salvaBt:disabled{opacity:.55;cursor:not-allowed} +.salvaBt:focus-visible{outline:2px solid var(--laranja2);outline-offset:2px} +@media(max-width:620px){.salvaBt{padding:0 9px;font-size:13px}}