/* 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, dialogHost, formDialog, 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(quotePage-1)*quoteSize+rows.length||rows.lengthsay(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&"eTotal){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)&¤tQuote.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); 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); 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);} const side=node('span',undefined,'qside'); side.append(node('b',q.approved?money(q.approved.total_cents):metres(quoteMetres(q)),'qm'), node('span',(quoteKind==='approved'?quoteExpiry(q):null)||shortAgo(q.created_at),'qt')); b.append(artBox(items,'qthumb'),main,side); b.onclick=()=>{currentQuote=q;$('tab-quotes').classList.toggle('reviewing',PHONE.matches);renderQuotes();};return b; }); const filtered=quoteQuery||quoteProduct||quoteLayout||quoteFlag; if(!list.length){ if(filtered)list.push(node('p','Nenhuma cotação com esses filtros.','empty pad')); else if(quoteKind==='pending'){ const waiting=board.approved_total||0; const action=button('Ver as '+waiting+' aguardando pagamento',async()=>{ quoteKind='approved';quotePage=1;quoteFitting=0;currentQuote=null; await loadQuotes(); },'btn'); list.push(emptyState(IC.check,'Tudo revisado', 'Nenhuma cotação esperando revisão. '+waiting+' estão aguardando pagamento.',action)); }else list.push(node('p','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,action){ 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)]:[]),...(action?[action]:[]));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',approved:'Aguardando pagamento',expired:'Expirada',paid:'Paga'}; function whatsappAction(quote){ const zap=whatsappLink(quote.draft.customer.zap); if(!zap)return null; const a=node('a','Abrir conversa','btn'); a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=quote.draft.customer.zap; a.prepend(svgIcon(IC.chat,'i m')); return a; } 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.mail].filter(Boolean).join(' · ')||who.title; title.append(h,node('span',QUOTE_STATUS[quote.status]||quote.status,'tag')); const pay=paymentBadge(quote.payment);if(pay)title.append(pay); const meta=node('div',undefined,'rmeta'); const doc=node('span');doc.append(docKind(c.cnpj)+' '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));meta.append(doc); // The e-mail stays in sight: for many customers it is the only way to tell them apart. if(who.mail&&who.mail!==who.title)meta.append(node('span',who.mail)); const dest=quote.draft.destination; meta.append(node('span',dest?'Entrega em '+dest.city+'/'+dest.state:'Retirada em Franca')); 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 body=node('div',undefined,'rbody'); const foot=node('div',undefined,'rfoot'); const chat=whatsappAction(quote); const withChat=parts=>{ if(chat){foot.append(node('span',undefined,'sp'),chat);parts.push(foot);} return parts; }; if(quote.status==='pending_review'&"e.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 withChat([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('manage')){ foot.append(discardButton(quote),node('span',undefined,'sp')); // 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',{}); // The quote is now that test order's: it leaves the list, and its // panel closes so nobody registers it again (Sentry DTF-WEB-D). currentQuote=null;say('Pedido de teste #'+order.number+' criado em Arte recebida.');await load(); },'btn'); foot.append(test); if(chat)foot.append(chat); if(may('enter'))foot.append(button('Pedido pago fora do site',()=>registerDialog(quote),'btn pri')); return [head,body,foot]; } return withChat([head,body]); } if(!may('manage')){ quote.draft.items.forEach((item,index)=>body.append(quoteItem(item,null,null,index,count))); return withChat([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)); // The times the customer accepted a warning are stamped by the server // (app/api/quotes.py) and not part of an item sent back (DTF-WEB-8). const {residue_accepted_at,stroke_choice_at,...sent}=item; return ()=>({...sent,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'); foot.append(checkbox('Arquivos, metragem e nota conferidos',check),...(chat?[chat]:[]),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. // Faturado is not one of them: an invoiced sale goes through the montador's // Venda (front 7a.3), and the API refuses it here (Sentry DTF-WEB-E). const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'}; function registerDialog(quote){ 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'; // The class keeps kanban.js' auto-refresh guard: the choices stay on screen. const body=node('div',undefined,'register'); body.append(group('origin','Origem',ORIGINS),group('method','Como foi pago',PAID_OUTSIDE),note); const pick=(form,name)=>form.querySelector('input[name="'+name+'-'+quote.id+'"]:checked')?.value; formDialog('Pedido pago fora do site',{host:dialogHost(),width:640, text:'Registre o pedido: ele entra em Arte recebida como os outros.', fields:[body],label:'Registrar pedido', onsave:async form=>{ const order=await api('/quotes/'+quote.id+'/register',{origin:pick(form,'origin'),method:pick(form,'method'),note:note.value}); currentQuote=null;say('Pedido #'+order.number+' registrado em Arte recebida.');await load(); }}); } 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'); } 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; const ihead=node('div',undefined,'ihead'); ihead.append(node('h3',productName(item))); if(count>1)ihead.append(node('span','item '+(index+1)+' de '+count,'ilbl')); info.append(ihead); 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); pair('Metros cobrados',priced?metres(priced.billed_metres):null); pair('Valor do metro',priced?money(priced.unit_cents)+manualExtra(priced):null); const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g); 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:String(Number(Number(item.metres).toFixed(3))),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'),summary=node('summary'); summary.append(node('span','Originais ('+item.uploads.length+')'),svgIcon(IC.right,'i s')); originals.append(summary); 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)':'';