Files
dtf-system/web/kanban-quotes.js
Cauê Faleiros fb3a5003b8 refactor: the Cotações tab in web/kanban-quotes.js
A pure move of kanban.js's Quotes section, byte-identical, loaded right
after kanban-numbers.js (Critical Corrections 7, second step). The browser
test opens Cotações so a missing name fails it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:08:05 -03:00

279 lines
19 KiB
JavaScript

/* Kanban DTF: the Cotações tab. The quotes list, the review panel, approval,
a test order and an order paid outside the site. Loaded after kanban.js,
which defines api, absorb, node, button, money, metres, say, ask, load, may,
$, ago, shortAgo, svgIcon, IC, iconButton, badge, gradePill, lowestGrade,
productLine, productName, sheetSize, buyer, docKind, cnpj, copyButton,
paymentBadge, freightWeight, whatsappLink, artBox, itemPreview, itemNote,
residueNote, field, checkbox, pager, download, downloadButton, xIcon, PHONE,
board, ORIGINS, LAYOUT_VERSIONS and the quote filters (quoteKind, quoteQuery,
quoteProduct, quoteLayout, quoteFlag). */
// ---- Quotes --------------------------------------------------------------
function quoteMetres(q){return (q.approved||q.draft).items.reduce((s,i)=>s+Number(i.billed_metres||i.metres),0);}
let quoteRows=[], quoteTotal=0, quotePage=1, quoteSize=0, currentQuote=null, quoteLoading=0, quoteFitting=0;
// Cotações never scrolls: a page holds as many quotes as the list's height fits.
// Before the first page, a guess from the height; after it, measured rows.
function guessQuoteSize(){return Math.max(3,Math.floor(($('quote-list').clientHeight||600)/88));}
function fitQuotes(){
const list=$('quote-list'), rows=[...list.querySelectorAll('.qrow')];
if($('tab-quotes').hidden||!rows.length||quoteFitting>3)return;
const room=list.clientHeight, gap=4;
const fits=rows.filter(r=>r.offsetTop-list.offsetTop+r.offsetHeight<=room).length;
const tallest=Math.max(...rows.map(r=>r.offsetHeight));
let size=quoteSize;
if(fits<rows.length)size=Math.max(1,fits);
else if(quoteTotal>(quotePage-1)*quoteSize+rows.length||rows.length<quoteSize){
const used=rows.at(-1).offsetTop-list.offsetTop+rows.at(-1).offsetHeight;
size=rows.length+Math.max(0,Math.floor((room-used)/(tallest+gap)));
}
if(size===quoteSize)return;
const first=(quotePage-1)*quoteSize;quoteSize=size;quotePage=Math.floor(first/size)+1;quoteFitting++;
loadQuotes().catch(e=>say(e.message,true));
}
let quoteResize=null;
addEventListener('resize',()=>{clearTimeout(quoteResize);quoteResize=setTimeout(()=>{quoteFitting=0;fitQuotes();},200);});
async function loadQuotes(){
const token=++quoteLoading;
if(!quoteSize)quoteSize=guessQuoteSize();
const params=new URLSearchParams({kind:quoteKind,limit:String(quoteSize),offset:String((quotePage-1)*quoteSize)});
for(const [key,value] of [['q',quoteQuery],['product',quoteProduct],['layout',quoteLayout],['flag',quoteFlag]])if(value)params.set(key,value);
const page=absorb(await api('/quotes?'+params));
if(token!==quoteLoading)return;
quoteRows=page.quotes;quoteTotal=page.total;
if(quotePage>1&&!quoteRows.length&&quoteTotal){quotePage=Math.ceil(quoteTotal/quoteSize);return loadQuotes();}
renderQuotes();
}
// What a quote needs looked at, in a word: shown on its row.
function quoteWarning(q){
const items=q.draft.items;
if(items.some(i=>!LAYOUT_VERSIONS.includes(i.production?.version)))return ['bad','Montagem antiga: peça uma nova cotação'];
if(!q.approved&&q.review_reason)return ['warn',q.review_reason];
if(items.some(i=>i.quality_status==='warning'))return ['warn','Ressalva de resolução aceita'];
return null;
}
// How long an approved quote has left before the worker expires it.
function quoteExpiry(q){
if(!q.expires_at)return null;
const left=new Date(q.expires_at).getTime()-Date.now();
if(left<=0)return 'expirando';
if(left<3600000)return 'expira em '+Math.max(1,Math.ceil(left/60000))+' min';
return 'expira em '+Math.ceil(left/3600000)+'h';
}
function renderQuotes(){
const kinds=[['pending','A revisar',board.pending_total],['approved','Aguardando pagamento',board.approved_total]];
$('quote-filters').replaceChildren(...kinds.map(([key,label,count])=>{
const b=node('button',label,quoteKind===key?'on':'');b.type='button';b.setAttribute('aria-pressed',String(quoteKind===key));
b.append(node('span',String(count??0),'n'));
b.onclick=()=>{quoteKind=key;quotePage=1;quoteFitting=0;currentQuote=null;loadQuotes().catch(e=>say(e.message,true));};return b;}));
// Product, layout and warning: each toggles; the two of a pair exclude each other.
const toggles=[['product','textil','Têxtil'],['product','uv','UV'],['layout','folha','Folha'],
['layout','avulsa','Avulsa'],['flag','ressalva','Com ressalva']];
const value={product:quoteProduct,layout:quoteLayout,flag:quoteFlag};
$('quote-chips').replaceChildren(...toggles.map(([group,key,label])=>{
const b=node('button',label,'tg'+(value[group]===key?' on':''));b.type='button';b.setAttribute('aria-pressed',String(value[group]===key));
b.onclick=()=>{const next=value[group]===key?'':key;
if(group==='product')quoteProduct=next;else if(group==='layout')quoteLayout=next;else quoteFlag=next;
quotePage=1;quoteFitting=0;loadQuotes().catch(e=>say(e.message,true));};return b;}));
// A customer opened from the top search: the list is theirs until the tag goes.
if(quoteQuery){const tag=node('button',quoteQuery,'ftag');tag.type='button';tag.setAttribute('aria-label','Tirar o filtro '+quoteQuery);
const x=node('span',undefined,'x');x.append(xIcon());tag.append(x);
tag.onclick=()=>{quoteQuery='';quotePage=1;quoteFitting=0;loadQuotes().catch(e=>say(e.message,true));};$('quote-chips').append(tag);}
if(!currentQuote||(!quoteRows.some(q=>q.id===currentQuote.id)&&currentQuote.status==='pending_review'))currentQuote=quoteRows[0]||null;
else currentQuote=quoteRows.find(q=>q.id===currentQuote.id)||currentQuote;
const list=quoteRows.map(q=>{
const b=node('button',undefined,'qrow'+(q.id===currentQuote?.id?' on':''));b.type='button';b.dataset.quotePick=q.id;
b.setAttribute('aria-current',String(q.id===currentQuote?.id));
const items=q.draft.items, who=buyer(q.draft);
const main=node('span',undefined,'qmain');
const first=node('span',undefined,'qline');
const name=node('b',who.title);name.title=who.mail||who.title;
// A quote from the last ten minutes carries a dot: someone just ordered.
if(Date.now()-new Date(q.created_at)<600000){const dot=node('span',undefined,'newdot');dot.title='Chegou agora';name.prepend(dot);}
first.append(name,node('span',q.approved?money(q.approved.total_cents):metres(quoteMetres(q)),'qm'));
const second=node('span',undefined,'qline sub');
const what=node('span');what.append(gradePill(lowestGrade(items)),' '+productLine(items)+', '+(q.draft.destination?q.draft.destination.city+'/'+q.draft.destination.state:'Retirada'));
second.append(what,node('span',(quoteKind==='approved'?quoteExpiry(q):null)||shortAgo(q.created_at)));
main.append(first,second);
const warn=quoteWarning(q);
if(warn){const w=node('span',undefined,'qwarn'+(warn[0]==='bad'?' bad':''));w.append(svgIcon(IC.alert,'i s'),node('span',warn[1]));main.append(w);}
const pay=paymentBadge(q.payment);
// Approved by the Site is the rule; only a person's review is worth a word.
if(pay||q.approved&&!q.auto_approved){const line=node('span',undefined,'qpay');
if(pay)line.append(pay);if(q.approved&&!q.auto_approved)line.append(badge('Revisada pela equipe',''));main.append(line);}
b.append(artBox(items,'qthumb'),main);
b.onclick=()=>{currentQuote=q;$('tab-quotes').classList.toggle('reviewing',PHONE.matches);renderQuotes();};return b;
});
const filtered=quoteQuery||quoteProduct||quoteLayout||quoteFlag;
if(!list.length)list.push(node('p',filtered?'Nenhuma cotação com esses filtros.':
quoteKind==='pending'?'Nenhuma cotação para revisar.':'Nenhuma cotação aprovada aguardando pagamento.','empty pad'));
$('quote-list').replaceChildren(...list);
$('quote-pager').replaceChildren(...(quoteTotal?[pager({page:quotePage,size:quoteSize,total:quoteTotal,noun:'cotações',compact:true,fixedSize:true,
onPage:n=>{quotePage=n;quoteFitting=0;loadQuotes().catch(e=>say(e.message,true));}})]:[]));
requestAnimationFrame(fitQuotes);
if(!currentQuote)$('tab-quotes').classList.remove('reviewing');
$('reviews').replaceChildren(...(currentQuote?[quoteHead(currentQuote),...review(currentQuote)]:[emptyState(IC.file,'Selecione uma cotação','A revisão dela abre aqui.')]));
}
// A page or a pane with nothing to show: a mark, a line, and what to do.
function emptyState(d,title,text){
const box=node('div',undefined,'emptystate'),ico=node('span',undefined,'dropico');ico.append(svgIcon(d));
box.append(ico,node('b',title),...(text?[node('span',text)]:[]));return box;
}
// The phone's head of a quote's page: back to the list, who, and WhatsApp.
function quoteHead(quote){
const h=node('div',undefined,'mhead phone'),t=node('span',undefined,'t'),who=buyer(quote.draft);
t.append(node('b',who.title),node('span',productLine(quote.draft.items)+', recebida '+ago(quote.created_at)));
h.append(iconButton(IC.left,'Voltar',()=>$('tab-quotes').classList.remove('reviewing'),'mic'),t);
const zap=whatsappLink(quote.draft.customer.zap);
if(zap){const a=node('a',undefined,'mic');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.setAttribute('aria-label','WhatsApp');a.append(svgIcon(IC.chat));h.append(a);}
return h;
}
const QUOTE_STATUS={pending_review:['A revisar','warn'],approved:['Aprovada, aguardando pagamento','ok'],expired:['Expirada','bad'],paid:['Paga','ok']};
function review(quote){
const head=node('div',undefined,'rhead');head.dataset.quote=quote.id;
const words=node('div',undefined,'rwords');
const who=buyer(quote.draft), c=quote.draft.customer;
const title=node('div',undefined,'rtitle');
const h=node('h2',who.title);h.title=who.legal||who.title;
const [label,tone]=QUOTE_STATUS[quote.status]||[quote.status,''];
const status=badge(label,tone);status.prepend(node('span',undefined,'dot'));
title.append(h,status);
const pay=paymentBadge(quote.payment);if(pay)title.append(pay);
const meta=node('div',undefined,'rmeta');
if(who.mail)meta.append(node('span',who.mail));
const doc=node('span');doc.append(docKind(c.cnpj)+' '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));meta.append(doc);
const dest=quote.draft.destination,where=node('span');where.append(svgIcon(dest?IC.truck:IC.pin,'i s'),dest?'Entrega em '+dest.city+'/'+dest.state:'Retirada em Franca');meta.append(where);
meta.append(node('span','Recebida '+ago(quote.created_at)),node('span','#'+quote.id.slice(0,8),'code'));
words.append(title,meta);head.append(words);
if(quote.approved){const total=node('div',undefined,'qbig');total.append(node('span','Total','lbl'),node('b',money(quote.approved.total_cents)));head.append(total);}
const zap=whatsappLink(c.zap);
if(zap){const a=node('a',quote.status==='approved'?'Abrir conversa':'WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=c.zap;a.prepend(svgIcon(IC.chat,'i m'));head.append(a);}
const body=node('div',undefined,'rbody');
const foot=node('div',undefined,'rfoot');
if(quote.status==='pending_review'&&quote.draft.items.some(item=>!LAYOUT_VERSIONS.includes(item.production?.version))){
body.append(callout(IC.alert,'Montagem antiga.','Solicite uma nova cotação ao cliente.','bad'));
return [head,body];
}
const count=quote.draft.items.length;
if(quote.status!=='pending_review'){
if(quote.status==='expired')body.append(callout(IC.alert,'Cotação expirada.','O cliente precisa solicitar outra.','bad'));
quote.draft.items.forEach((item,index)=>body.append(quoteItem(item,null,quote.approved?.items?.[index],index,count)));
if(quote.approved){
const sums=node('div',undefined,'qsums');const fr=quote.approved.freight||{};
const itemsTotal=quote.approved.items.reduce((t,i)=>t+i.total_cents,0);
sums.append(node('span','Itens'),node('b',money(itemsTotal)),
node('span',fr.service==='pickup'||!fr.total_cents?'Retirada':'Frete Jadlog'+(fr.weight_kg?', '+freightWeight(fr):'')),
node('b',fr.total_cents?money(fr.total_cents):'grátis'),node('span','Total'),node('b',money(quote.approved.total_cents)));
body.append(sums);
}
if(quote.status==='approved'&&may('enter'))body.append(registerForm(quote));
if(quote.status==='approved'&&may('manage')){
foot.append(discardButton(quote));
// Tries the whole production flow without a payment.
const test=button('Criar pedido de teste',async()=>{
if(!await ask('Criar um pedido de teste?','Ele entra em Arte recebida sem cobrar nada e não vai para o Tiny.','Criar pedido de teste'))return;
const order=await api('/quotes/'+quote.id+'/test-order',{});
say('Pedido de teste #'+order.number+' criado em Arte recebida.');await load();
},'btn right');
foot.append(test);
return [head,body,foot];
}
return [head,body];
}
if(!may('manage')){
quote.draft.items.forEach((item,index)=>body.append(quoteItem(item,null,null,index,count)));
return [head,body];
}
const form=node('form',undefined,'rform');
const edits=quote.draft.items.map((item,index)=>{const fields={};body.append(quoteItem(item,fields,null,index,count));
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});
const check=node('input');check.required=true;
const submit=node('button','Aprovar cotação','btn pri lg');
foot.append(checkbox('Arquivos, metragem e nota conferidos',check),discardButton(quote),submit);
form.append(body,foot);
form.onsubmit=async e=>{e.preventDefault();submit.disabled=true;
try{const approved=await api('/quotes/'+quote.id+'/approve',{items:edits.map(fn=>fn())});
// Keep showing the quote just approved while its list refreshes.
currentQuote={...quote,approved,status:'approved'};say('Cotação aprovada.');await load();}
catch(error){say(error.message,true);submit.disabled=false;}};
return [head,form];
}
function callout(d,title,text,tone=''){
const box=node('div',undefined,'callout'+(tone?' '+tone:'')),ico=node('span',undefined,'cico');ico.append(svgIcon(d,'i m'));
const p=node('p');p.append(node('b',title+' '),text||'');box.append(ico,p);return box;
}
// An order paid outside the site (Dropstar's rule D-35): the team builds the
// cart on the Site, as a customer would, and registers it here. Origin and
// payment start unchosen: a default would become the answer to everything.
const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente',faturado:'Faturado'};
function registerForm(quote){
const form=node('form',undefined,'register');
const group=(name,label,options)=>{
const g=node('div',undefined,'fgroup2');g.setAttribute('role','radiogroup');g.setAttribute('aria-label',label);
const set=node('div',undefined,'fopts');
for(const [value,text] of Object.entries(options)){
const l=node('label',undefined,'fopt'),r=node('input');
r.type='radio';r.name=name+'-'+quote.id;r.value=value;r.required=true;r.className='vh';l.append(r,text);set.append(l);}
g.append(node('span',label,'lbl'),set);return g;};
const note=node('input');note.type='text';note.maxLength=300;note.placeholder='Observação (opcional)';note.setAttribute('aria-label','Observação');note.className='inp';
const submit=node('button','Registrar pedido','btn pri');
const row=node('div',undefined,'decide');row.append(note,submit);
const head=node('div');head.append(node('h4','Pago fora do site?'),node('p','Registre o pedido: ele entra em Arte recebida como os outros.','nnote'));
form.append(head,group('origin','Origem',ORIGINS),group('method','Como foi pago',PAID_OUTSIDE),row);
form.onsubmit=async e=>{e.preventDefault();
const pick=name=>form.querySelector('input[name="'+name+'-'+quote.id+'"]:checked')?.value;
submit.disabled=true;
try{const order=await api('/quotes/'+quote.id+'/register',{origin:pick('origin'),method:pick('method'),note:note.value});
currentQuote=null;say('Pedido #'+order.number+' registrado em Arte recebida.');await load();}
catch(error){say(error.message,true);submit.disabled=false;}};
return form;
}
const paidOutside=order=>order.payment?.provider==='manual';
// An unpaid quote leaves the list and can no longer be paid.
function discardButton(quote){
return button('Descartar cotação',async()=>{
if(!await ask('Descartar esta cotação?','Ela sai do Kanban e o cliente não consegue mais pagá-la.','Descartar cotação',{tone:'red'}))return;
await api('/quotes/'+quote.id+'/discard',{});currentQuote=null;say('Cotação descartada.');await load();
},'btn quiet right');
}
function quoteItem(item,fields,priced,index=0,count=1){
const box=node('section',undefined,'ritem');box.setAttribute('aria-label','Item '+(index+1));
const tall=node('div',undefined,'tall');tall.tabIndex=0;tall.setAttribute('aria-label','Montagem da folha. Role para ver tudo.');
tall.append(itemPreview(item));
const info=node('div',undefined,'iinfo');
const spec=item.production;
info.append(node('span',count>1?'Item '+(index+1)+' de '+count:'Item','lbl'),node('h3',productName(item)));
const dl=node('dl',undefined,'dl');
const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);};
pair('Folha',sheetSize(spec));pair('Peças',spec?String(spec.placements.length):null);
pair('Arquivos',spec?String(spec.sources.length):null);
const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g);
pair('Metros cobrados',priced?metres(priced.billed_metres):null);
pair('Valor do metro',priced?money(priced.unit_cents)+manualExtra(priced):null);
pair('Valor',priced?money(priced.total_cents):null);
info.append(dl);
const notes=node('div',undefined,'inotes');
notes.append(item.quality_status==='ok'?itemNote('Qualidade conferida','ok'):item.quality_status==='warning'?
itemNote(item.quality_acknowledged?'Ressalva de resolução aceita pelo cliente':'Ressalva de resolução não aceita','warn'):itemNote('Qualidade não conferida'));
if(item.residue_accepted)notes.append(itemNote('Resíduo aceito pelo cliente: '+residueNote(item)+'.','warn'));
info.append(notes);
if(fields){
const grid=node('div',undefined,'inputs');
fields.metres=node('input');Object.assign(fields.metres,{type:'number',min:'0.001',max:'12000',step:'any',value:item.metres,required:true});
fields.grade=node('input');Object.assign(fields.grade,{type:'number',min:'0',max:'100',step:'1',value:item.grade,required:true});
const m=field('Metros conferidos',fields.metres,'O cliente pediu '+metres(item.metres));
const low=Number(item.grade)<60;
const gr=field('Nota conferida',fields.grade,low?'Nota baixa: confira a resolução':'A nota que o Site deu');
if(low)gr.classList.add('warn');
grid.append(m,gr);info.append(grid);
}
const links=node('div',undefined,'links');
const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')'));
item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid),'btn')));
links.append(originals);
info.append(links);box.append(tall,info);return box;
}
// A finished sheet someone opens by hand pays this per metre on top (app/core/pricing.py).
const manualExtra=item=>item?.manual_extra_cents?' (com '+money(item.manual_extra_cents)+' de arquivo manual)':'';