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 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 16:09:52 -03:00
parent 5671235681
commit 3428ff68be
5 changed files with 156 additions and 8 deletions

View File

@@ -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;}
})();

View File

@@ -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)

View File

@@ -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(){
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span>'+
(semMargem(it)?'<span class="avisoF">O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.</span>':'')+'</div>'+
'<div class="vl2">'+rs(it.total)+'</div>'+
(window.dtfContaAberta?'<button type="button" class="salvaBt" data-salvai="'+i+'"'+
(podeSalvarFolha(it)?'':' disabled title="Espere os arquivos terminarem de enviar."')+
'>Salvar em Minhas folhas</button>':'')+
'<button type="button" class="x" data-rmi="'+i+'" aria-label="Remover '+escapeHTML(it.tit)+'">'+icone('lixeira')+'<span>Remover</span></button></div>').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;

View File

@@ -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=<id>. 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);
});

View File

@@ -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}}