/* Meus pedidos: the customer's orders, their progress and files, sign-in and
the artwork correction the team may ask for. */
const $=id=>document.getElementById(id);
const node=(tag,text,className)=>{const el=document.createElement(tag);if(text!==undefined&&text!==null)el.textContent=text;if(className)el.className=className;return el;};
const money=c=>(c/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
const quando=d=>new Date(d).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit'});
const dia=d=>new Date(d).toLocaleDateString('pt-BR');
const metros=m=>Number(m).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m';
// Lucide shapes (ISC licence), the same as on the Site.
const ICONES={
baixar:'',
local:'',
caminhao:'',
ok:'',
alerta:'',
relogio:'',
};
function icone(nome){
const span=document.createElement('span');span.className='icw';
span.innerHTML='';
return span.firstChild;
}
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
// The order's way through production, as the customer sees it.
const TRILHA=['rec','tra','fil','imp','fin'];
let scope,states={},environment='';
async function api(path,body){const r=await fetch('/api'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos informados.');error.status=r.status;throw error;}return d;}
const aviso=text=>{$('message').textContent=text||'';};
function button(text,fn,className='bSec'){const b=node('button',text,className);b.type='button';b.onclick=async()=>{b.disabled=true;try{await fn();}catch(e){aviso(e.message);}finally{b.disabled=false;}};return b;}
function forgetCheckout(){for(const k of ['dtf-quote','dtf-request-key','dtf-request-body'])localStorage.removeItem(k);}
function trilha(state){
const ol=node('ol',null,'trilha');
const atual=state==='cor'?-1:TRILHA.indexOf(state);
TRILHA.forEach((s,i)=>{
const li=node('li',null,i{
if(content.childElementCount){content.replaceChildren();ver.textContent='Ver detalhes e arquivos';return;}
await details(order.id,content,order.created_at);ver.textContent='Fechar detalhes';
},'bLink');
card.append(ver,content);orders.append(card);
if(aberto===order.id){await details(order.id,content,order.created_at);ver.textContent='Fechar detalhes';card.scrollIntoView({block:'start'});}
}
}catch(error){aviso(error.message);}
}
async function details(id,container,criado){
const order=await api('/customer/orders/'+id);container.replaceChildren();
const hist=node('div',null,'secao');hist.append(node('h4','Andamento'));
const ol=node('ol',null,'historico');
// Payment is where the order starts: the first step is not a movement.
if(criado){const li=node('li');li.append(node('b',states.rec||'Arte recebida'),node('span',quando(criado)));ol.append(li);}
for(const h of order.history){
const li=node('li');li.append(node('b',states[h.to_state]),node('span',quando(h.created_at)));
if(h.reason)li.append(node('p',h.reason,'motivo'));
ol.append(li);
}
hist.append(ol);container.append(hist);
if(order.files.length){
const arq=node('div',null,'secao');arq.append(node('h4','Arquivos'));
for(const file of order.files){
const row=node('div',null,'arquivo');
const info=node('div');
info.append(node('b',file.name),node('span',(file.kind==='final'?'Arquivo final':'Correção')+' · item '+(file.item_index+1)+' · '+
(file.expired?'expirado':!file.active?'substituído':'disponível até '+dia(file.expires_at))));
row.append(info);
if(file.active&&!file.expired){
const b=button('Baixar',async()=>{const d=await api('/customer/orders/'+id+'/files/'+file.id+'/download');const link=node('a');link.href=d.url;link.download=d.name;link.referrerPolicy='no-referrer';link.click();});
b.prepend(icone('baixar'));row.append(b);
}
arq.append(row);
}
container.append(arq);
}
if(order.state==='cor'){
const form=node('form',null,'secao correcaoForm');form.append(node('h4','Enviar arte corrigida'));
const inputs=order.snapshot.items.map((item,index)=>{
const label=node('label',(index+1)+'. '+(PRODUTO[item.mode]||item.mode));
const input=node('input');input.type='file';input.multiple=true;input.dataset.item=index;
form.append(label,input);return input;
});
const nl=node('label','O que foi corrigido');const note=node('textarea');note.required=true;note.maxLength=1000;note.rows=3;
form.append(nl,note);
const submit=node('button','Enviar correção','bPri');submit.type='submit';form.append(submit);
form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;try{
const files=[];for(const [index,input] of inputs.entries())for(const file of input.files)files.push({item_index:index,upload_id:await dtfUpload(file,{api,scope:scope+':correction:'+id+':'+order.version,progress:text=>aviso(text)})});
if(!files.length)throw new Error('Selecione pelo menos um arquivo corrigido.');
await api('/customer/orders/'+id+'/corrections',{version:order.version,files,note:note.value});
aviso('Correção enviada. Aguarde a conferência da equipe.');await details(id,container,criado);
}catch(error){aviso(error.message);}finally{submit.disabled=false;}};
container.append(form);
}
}
async function migrateGuestCart(previous,next){
if(previous===next)return;
const database=await new Promise((resolve,reject)=>{const r=indexedDB.open('dtf-local-cart',1);r.onupgradeneeded=()=>r.result.createObjectStore('cart');r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});
await new Promise((resolve,reject)=>{const tx=database.transaction('cart','readwrite'),store=tx.objectStore('cart'),req=store.get(previous);req.onsuccess=()=>{if(req.result){store.put(req.result,next);store.delete(previous);}};tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);});
database.close();
}
async function authenticate(path,body){
const previous=scope,guest=!(await api('/account/me')).customer;
await api(path,body);forgetCheckout();aviso('Acesso confirmado.');
const next=(await api('/session')).cart_scope;
if(guest)try{await migrateGuestCart(previous,next);}catch{aviso('Acesso confirmado. Não foi possível transferir o carrinho salvo neste navegador.');}
await load();$('password').value='';$('register-password').value='';
}
$('login').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/login',{email:$('email').value,password:$('password').value});}catch(e){aviso(e.message);}};
$('register').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/register',{customer:{cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});}catch(e){aviso(e.message);}};
$('logout').onclick=async()=>{try{await window.dtfForgetPrivateData();await api('/account/logout',{});location.reload();}catch(error){aviso('Não foi possível limpar os dados deste navegador. Feche as abas do Site e limpe os dados do site nas configurações do navegador.');}};
$('refresh').onclick=load;
load();