Merge branch 'main' into bug-66

This commit is contained in:
Cauê Faleiros
2026-11-11 16:43:33 -03:00
5 changed files with 884 additions and 859 deletions

View File

@@ -344,6 +344,16 @@ try{
await kanban.click('[data-tab="stats"]');
await waitFor(()=>kanban.eval(`document.querySelector('#stats-kpis').children.length>0
&& document.querySelector('#stats-machine-body').children.length>0`),'Números tab and machines by month');
// Cotações lives in its own file now: the list and the review panel load too.
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval(`document.querySelector('#quote-filters').children.length>0
&& document.querySelector('#quote-list').children.length>0
&& document.querySelector('#reviews').children.length>0`),'Cotações tab and review panel');
// Usuários, machines and each machine's sheet live in their own file too.
await kanban.click('[data-tab="users"]');
await waitFor(()=>kanban.eval(`document.querySelector('#users-list').children.length>0
&& document.querySelector('#roles-matrix').children.length>0
&& document.querySelector('#machines-list').children.length>0`),'Usuários tab, people, roles and machines');
// A guest sees the order paid in this browser; creating an account keeps it.
const portal=await page(siteOrigin+'/conta/pedidos?order='+oid);
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking');

278
web/kanban-quotes.js Normal file
View File

@@ -0,0 +1,278 @@
/* 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)':'';

595
web/kanban-users.js Normal file
View File

@@ -0,0 +1,595 @@
/* Kanban DTF: the Usuários tab. People, print machines and each machine's
sheet (front 1a). Loaded after kanban.js, which defines $, api, node,
button, svgIcon, IC, iconButton, emptyState, may, money, when, ago, say,
plural, metres, field, checkbox, formDialog, modal, dialogHost, ask, board,
ME, myMachine, move, load, openFilters, closeFilters, ROLE_NAMES and kanbanTheme (theme.js). */
// ---- Machines and users ----------------------------------------------------
// "Em qual máquina você está?" (Dropstar's third round, item 12): after signing
// in, required for the operator, and for Gestão and the administrators with
// "Não estou em máquina". Per session: one person on two computers runs two
// machines. Someone else already on the machine is a warning, not a refusal.
let askingMachine=false;
function askMachine(again=false){
if(!ME?.machine_question||askingMachine||(ME.machine_answered&&!again))return;
askingMachine=true;
const required=ME.machine_question==='required', current=myMachine();
let m=null;
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});m.close();await load(true);}
catch(e){
if(e.status===409&&!confirm&&await ask('Outra pessoa está nesta máquina',e.message,'Continuar mesmo assim'))return choose(id,true);
say(e.message,true);}};
// Each machine with what it is printing, and who is on it now.
const list=node('div',undefined,'mchoices');
for(const machine of (board.machines||[]).filter(x=>x.active)){
const mine=current?.id===machine.id;
const b=node('button',undefined,'mchoice'+(mine?' on':''));b.type='button';b.setAttribute('aria-pressed',String(mine));
const head=node('span',undefined,'mhead');head.append(node('b',machine.name));
if(mine){const tick=node('span',undefined,'tick');tick.append(svgIcon(IC.check,'i s'));head.append(tick);}
b.append(head,node('span',machine.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','sub'));
const here=board.orders.filter(o=>o.state==='imp'&&!o.cancelled_at&&o.machine?.id===machine.id)
.sort((x,y)=>(x.printing==='imprimindo'?0:1)-(y.printing==='imprimindo'?0:1));
for(let i=0;i<Math.max(board.printing_cap||2,here.length);i++){
const o=here[i],job=node('span',undefined,'job');
if(o)job.append(node('i',undefined,o.printing==='ripando'?'ripmark':'runmark'),node('span','#'+o.number,'code'),node('em',o.printing==='ripando'?'ripando':'imprimindo'));
else job.append(node('i',undefined,'freemark'),node('span','livre','free'));
b.append(job);
}
if(machine.operators){const others=machine.operators.filter(op=>op.name!==(ME.name||ME.email));
b.append(node('span',others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'Ninguém mais nela','who'));}
b.onclick=()=>choose(machine.id);list.append(b);
}
if(!list.children.length)list.append(node('p','Nenhuma máquina ativa. Peça ao Administrador para cadastrar em Usuários, Máquinas.','empty'));
const foot=[];
if(!required)foot.push(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(required&&!ME.machine_answered)foot.push(button('Sair',()=>$('logout').click(),'btn ghost'));
if(current&&ME.machine_answered)foot.push(button('Continuar na '+current.name,async()=>m.close(),'btn pri right'));
m=modal('Em qual máquina você está?',{text:'O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.',
body:[list],foot,width:620,locked:required&&!ME.machine_answered,onclose:()=>{askingMachine=false;}});
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const asked=!!ME?.machine_question, mine=myMachine();
for(const id of ['my-machine','rail-machine','account-machine'])$(id).hidden=!asked;
if(!asked)return;
const name=mine?mine.name:'Sem máquina';
const chip=$('my-machine');chip.replaceChildren(node('i'),node('span','Máquina '),node('b',name));
chip.classList.toggle('on',!!mine);
chip.title=mine?'Você está na '+mine.name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
const rail=$('rail-machine');rail.querySelector('b').textContent=mine?mine.name:'Nenhuma';rail.classList.toggle('on',!!mine);rail.title=chip.title;
$('account-machine').querySelector('.lbl').textContent=mine?mine.name:'';
}
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
// The machine is recorded when the card is pulled into Imprimindo.
function machineCard(order){
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
const current=order.machine;
const pulled=order.machine_pulled;
const detail=pulled?'Puxada por '+pulled.by+' em '+when(pulled.at):current?'Escolhida para este pedido':'Definida quando alguém puxar o card';
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail));
return box;
}
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Sem máquina');auto.value='';select.append(auto);
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
}
select.value=current?.id||'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'O pedido aguarda uma máquina.');await load();}
catch(e){say(e.message,true);}};
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail),select);
return box;
}
// "120,00 m de 300,00 m" or "120,00 m em aberto".
function machineLoad(m){
return m.limit_metres?metres(m.open_metres)+' de '+metres(m.limit_metres):metres(m.open_metres)+' em aberto';
}
// Chips that switch on and off (what a machine prints): .values() is what is on.
function pills(options,selected){
const box=node('div',undefined,'fopts'),on=new Set(selected);
for(const [value,label] of options){
const b=node('button',label,'fopt'+(on.has(value)?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on.has(value)));
b.onclick=()=>{if(on.has(value))on.delete(value);else on.add(value);b.classList.toggle('on',on.has(value));b.setAttribute('aria-pressed',String(on.has(value)));};
box.append(b);
}
box.values=()=>options.map(([v])=>v).filter(v=>on.has(v));return box;
}
// A dialog field that is a group (chips, a list) rather than one input.
function group(label,...content){const g=node('div',undefined,'fld');g.append(node('span',label),...content);return g;}
// A list to choose from, drawn by us: each choice with a line on what it means.
function choice(options,value,{label,disabled=false}={}){
const wrap=node('div',undefined,'sel');let current=value;
const btn=node('button',undefined,'selbtn');btn.type='button';btn.disabled=disabled;
btn.setAttribute('aria-haspopup','listbox');btn.setAttribute('aria-expanded','false');if(label)btn.setAttribute('aria-label',label);
const text=node('span');btn.append(text,svgIcon(IC.down,'i m'));
const list=node('div',undefined,'pop sellist');list.setAttribute('role','listbox');list.hidden=true;
const hint=node('small');
const close=()=>{list.hidden=true;btn.classList.remove('open');btn.setAttribute('aria-expanded','false');};
const paint=()=>{const o=options.find(x=>x.value===current)||options[0];text.textContent=o.label;hint.textContent=o.hint||'';
for(const b of list.children){const on=b.dataset.value===current;b.setAttribute('aria-selected',String(on));b.querySelector('.ck').replaceChildren(...(on?[svgIcon(IC.check,'i m')]:[]));}};
for(const o of options){
const b=node('button',undefined,'selopt');b.type='button';b.setAttribute('role','option');b.dataset.value=o.value;
const words=node('span');words.append(node('b',o.label),...(o.hint?[node('small',o.hint)]:[]));
b.append(node('span',undefined,'ck'),words);
b.onclick=()=>{current=o.value;paint();close();btn.focus();};list.append(b);
}
btn.onclick=e=>{e.stopPropagation();if(!list.hidden)return close();list.hidden=false;btn.classList.add('open');btn.setAttribute('aria-expanded','true');
list.querySelector('[aria-selected=true]')?.focus();
setTimeout(()=>document.addEventListener('click',close,{once:true}));};
list.onkeydown=e=>{const items=[...list.children],i=items.indexOf(document.activeElement);
if(e.key==='ArrowDown'){e.preventDefault();items[Math.min(items.length-1,i+1)].focus();}
if(e.key==='ArrowUp'){e.preventDefault();items[Math.max(0,i-1)].focus();}};
wrap.append(btn,list);paint();
wrap.value=()=>current;wrap.hint=hint;wrap.close=close;wrap.isOpen=()=>!list.hidden;
return wrap;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
// What each profile is for, in a line (app/core/auth.py).
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa, libera para Finalizado e reimprime a etiqueta.',
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
expedicao:'Monta folhas no Kanban e imprime a etiqueta; só consulta o resto.'};
// Who is on the system: used it in the last 15 minutes, signed in before,
// never, or switched off.
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
const presence=u=>!u.active?'off':u.seen_at&&Date.now()-new Date(u.seen_at)<15*60e3?'on':u.last_login_at?'away':'never';
const initialsOf=text=>String(text||'').trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'·';
function avatar(u,className='ava'){
const a=node('span',initialsOf(u.name||u.email),className),p=node('i',undefined,'pres '+presence(u));
p.title=PRESENCE[presence(u)];a.append(p);return a;
}
// "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py).
const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY'],
['Imprimir a etiqueta 10×15','YYNNYNNY']];
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
renderUsers();
}
function renderUsers(){
const {users,machines}=usersData;
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
$('users-count').textContent=String(users.length);
$('users-list').replaceChildren(...users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const who=node('td'),line=node('span',undefined,'who'),words=node('span');
words.append(node('b',u.name||u.email),node('span',u.email,'sub'));line.append(avatar(u),words);who.append(line);
const machine=node('td');
if(u.machines.length){const m=node('span',undefined,'mcell');m.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));machine.append(m);}
else machine.append(node('span','Sem máquina','muted'));
const open=node('td',undefined,'r');
if(editable){open.append(iconButton(IC.right,'Editar '+(u.name||u.email),()=>userForm(u),'btn sq ghost'));tr.classList.add('click');tr.onclick=()=>userForm(u);}
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':', desativado')),machine,
node('td',u.last_login_at?ago(u.last_login_at):'nunca entrou','muted'),open);
return tr;
}));
// On the phone, a list of people, each a row that opens them.
const list=$('users-phone');list.replaceChildren(...users.map(u=>{
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const row=node('button',undefined,'mli');row.type='button';row.disabled=!editable;if(editable)row.onclick=()=>userForm(u);
const words=node('span',undefined,'grow'),sub=node('span',undefined,'sub mcell');
sub.append(ROLE_NAMES[u.role]+(u.active?'':', desativado'));
if(u.machines.length){sub.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));}
words.append(node('b',u.name||u.email),sub);
row.append(avatar(u),words,svgIcon(IC.right,'i m'));return row;}));
const head=node('tr');head.append(node('th',''));for(const r of ROLE_COLUMNS)head.append(node('th',ROLE_NAMES[r]));
for(const th of head.children)th.scope='col';head.firstChild.append(node('span','Ação','vh'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const [label,cells] of ROLE_MATRIX){const tr=node('tr');tr.append(node('td',label));
[...cells].forEach(k=>{const td=node('td'),i=node('i',undefined,k==='Y'?'can':k==='V'?'can view':'can no');
td.title=k==='Y'?'Faz':k==='V'?'Só consulta':'Não';td.append(i,node('span',td.title,'vh'));tr.append(td);});tbody.append(tr);}
$('roles-matrix').replaceChildren(thead,tbody);
$('machines-count').textContent=String(machines.length);
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
:[emptyState(IC.printer,'Nenhuma máquina cadastrada','Cadastre as máquinas para os pedidos irem para elas.')]));
}
// A machine: its metres open against its limit, its orders by stage, and who is on it.
const STAGE_FILL={rec:'var(--tx3)',tra:'var(--ln3)',imp:'var(--ink)',cor:'var(--bad)',rev:'var(--tx2)'};
function machineTile(m){
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
const head=node('div',undefined,'row');
head.append(node('h3',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','lbl'));
if(!m.active)head.append(badge('Desativada',''));
head.append(button('Ficha',()=>openMachineSheet(m.id),'btn ghost right'),button('Editar',()=>machineForm(m),'btn ghost'));
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const load=node('div',undefined,'row base');
load.append(node('b',metres(m.open_metres),over?'bad':''),node('span','em aberto, '+(m.limit_metres?'limite de '+metres(m.limit_metres)+(over?', acima do limite':''):'sem limite'),'lbl'));
const stages=Object.keys(STAGE_FILL).filter(s=>m.states[s]);
const total=stages.reduce((t,s)=>t+m.states[s],0);
tile.append(head,load);
if(total){
const stack=node('div',undefined,'stack'),list=node('ul');
for(const s of stages){const seg=node('i');seg.style.width=(100*m.states[s]/total)+'%';seg.style.background=STAGE_FILL[s];stack.append(seg);
const li=node('li'),dot=node('i');dot.style.background=STAGE_FILL[s];li.append(dot,board?.states?.[s]||s,node('b',String(m.states[s])));list.append(li);}
tile.append(stack,list);
}else tile.append(node('span','Nenhum pedido em aberto','lbl'));
const people=node('div',undefined,'row people');people.append(svgIcon(IC.user,'i s'),
m.operators?.length?m.operators.map(o=>o.name+(o.since?' desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'')).join(', ')+(m.operators.length>1?' estão nela':' está nela'):'Ninguém nela agora');
tile.append(people);
return tile;
}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br';
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador',
{label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email});
const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint);
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter a atual':'8 caracteres ou mais';
const active=node('input');active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const row=node('div',undefined,'frow');row.append(field('Nome',name),field('E-mail',email));
const left=[];
if(editing&&u.email!==ME.email){
const remove=node('button','Excluir usuário','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir '+(u.name||u.email)+'?','A pessoa não entra mais no sistema. Os pedidos continuam com o nome dela no histórico. Para só bloquear o acesso, desmarque Ativo.','Excluir usuário',{tone:'red'}))return;
try{await api('/users/'+u.id+'/delete',{});m.close();say('Usuário excluído.');await loadUsers();}catch(e){say(e.message,true);}};
left.push(remove);
}
const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null,
text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.',
fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),checkbox('Ativo: pode entrar no sistema',active)],
label:editing?'Salvar':'Criar usuário',onsave:async()=>{
const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
}});
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';name.placeholder='Ex.: Têxtil 2';
const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]);
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const active=node('input');active.checked=m?m.active:true;
const left=[];
if(m){
const remove=node('button','Excluir máquina','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir a máquina '+m.name+'?','Os pedidos dela vão para outra máquina do produto.','Excluir máquina',{tone:'red'}))return;
try{await api('/machines/'+m.id+'/delete',{});d.close();say('Máquina excluída.');await loadUsers();await load();}catch(e){say(e.message,true);}};
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
checkbox('Ativa: recebe pedidos',active)],
onsave:async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
}});
}
// ---- Machine sheet (Fase 2, front 1a) --------------------------------------
//
// What goes into a machine, what the room has printed since the last clean and
// the last film roll, and the alerts that wait between one file and the next.
// The numbers per machine (cost, ROI) are part b and stay in Números.
function machineEntryLine(entry, catalog){
const label=entry.label||entry.item;
let detail='';
if(entry.kind==='supply'){
const unit=catalog.supplies[entry.item]?.[1]||'';
detail=Number(entry.quantity).toLocaleString('pt-BR',{maximumFractionDigits:3})+' '+unit;
if(entry.cost_cents!==null&&entry.cost_cents!==undefined)detail+=' · '+money(entry.cost_cents);
}else if(entry.kind==='part'){
detail=(entry.note?entry.note+' · ':'')+(entry.serial?'série '+entry.serial+' · ':'')+money(entry.cost_cents);
}else if(entry.item==='stop'){
detail=entry.stop_minutes+' min'+(entry.note?' · '+entry.note:'');
}
return [when(entry.created_at),label,detail,entry.created_by].filter(Boolean).join(' · ');
}
async function openMachineSheet(machineId){
let data;
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return;}
const machine=data.machine;
const launch=may('print')&&(ME?.role!=='operador'||myMachine()?.id===machine.id);
const body=[];
let sheetModal=null;
const refresh=async()=>{sheetModal?.close();await load();openMachineSheet(machine.id);};
const minimum=value=>Number(value).toLocaleString('pt-BR',{maximumFractionDigits:3});
const counts=node('div',undefined,'mblock');
const fact=(label,value)=>{const row=node('div',undefined,'mfact');row.append(node('span',label),node('b',value));counts.append(row);};
const clean=data.counters.clean, film=data.counters.film;
fact('Desde a última limpeza',m1(clean.metres)+' m'+(clean.since?'':' (nenhuma limpeza lançada ainda)'));
fact('Desde a troca de filme',film.since?m1(film.metres)+' m '+(film.aligned?'(cabeça alinhada)':'(falta alinhar)'):'sem registro');
body.push(node('h4','Contadores','sh'),counts);
const supplies=node('div',undefined,'mblock');
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const value=data.supplies[item];
const row=node('div',undefined,'mfact');
let text;
if(value){
text='acaba em ~'+m1(value.metres_left)+' m';
if(value.minimum!==null&&value.minimum!==undefined)text+=' · mínimo '+minimum(value.minimum)+' '+unit;
}else text='lance duas reposições para estimar';
row.append(node('span',label),node('b',text));
supplies.append(row);
}
body.push(node('h4','Insumos','sh'),supplies);
if(data.alerts.length){
const box=node('div',undefined,'mblock');
const done=async alert=>{
if(alert.key.startsWith('supply:')){
const saved=await machineEntryForm(machine.id,{kind:'supply',item:alert.key.slice(7),from_alert:true},data);
if(!saved)return;
}else{
await api('/machines/'+machine.id+'/entries',{kind:'event',item:alert.key,from_alert:true});
}
say('Aviso resolvido.');
await refresh();
};
for(const alert of data.alerts){
const row=node('div',undefined,'sheetalert');
const words=node('span',undefined,'grow');
words.append(node('b',alert.text),node('span',alert.blocking?'pendente':'adiado neste ciclo','sub'));
row.append(words);
if(launch){
const actions=node('span',undefined,'prow');
actions.append(button('Marcar como feito',()=>done(alert),'btn'));
if(alert.snoozable)actions.append(button('Adiar uma vez',async()=>{
await api('/machines/'+machine.id+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
say('Aviso adiado: passa um arquivo e ele volta.');
await refresh();
},'btn ghost'));
row.append(actions);
}
box.append(row);
}
body.push(node('h4','Avisos pendentes','sh'),box);
}
const entries=node('div',undefined,'mlist sheetentries');
if(data.entries.length)for(const entry of data.entries)entries.append(node('div',machineEntryLine(entry,data.catalog),'mli'));
else entries.append(node('div','Nenhum lançamento ainda','mli muted'));
body.push(node('h4','Lançamentos','sh'),entries);
if(launch){
const prow=node('div',undefined,'prow');
prow.append(button('Lançar',async()=>{
const saved=await machineEntryForm(machine.id,{},data);
if(!saved)return;
say('Lançamento registrado.');
await refresh();
},'btn pri'));
body.push(prow);
}
if(may('manage')){
const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal';
price.value=data.machine.price_cents!==null&&data.machine.price_cents!==undefined?(data.machine.price_cents/100).toFixed(2):'';
const installed=node('input');installed.type='date';installed.value=data.machine.installed_on||'';
const minimums={};
const box=node('div',undefined,'mblock');
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
// Dropstar's fixed minimums are the defaults: a machine with none typed
// shows and uses them until Gestão changes them.
const typed=data.minimums[item], fallback=data.default_minimums?.[item];
input.value=typed!==null&&typed!==undefined?Number(typed).toString()
:fallback!==null&&fallback!==undefined?Number(fallback).toString():'';
minimums[item]=input;
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
}
const error=node('span',undefined,'warn');error.hidden=true;
const save=node('button','Salvar','btn pri');save.type='button';
save.onclick=async()=>{
save.disabled=true;error.hidden=true;
try{
await api('/machines/'+machine.id+'/sheet',{
price_cents:price.value.trim()===''?null:Math.round(Number(price.value)*100),
installed_on:installed.value||null,
minimums:Object.fromEntries(Object.entries(minimums).map(([item,input])=>
[item,input.value.trim()===''?null:Number(input.value)]))});
say('Dados da máquina salvos.');
await refresh();
}catch(e){error.textContent=e.message;error.hidden=false;}
finally{save.disabled=false;}
};
const foot=node('div',undefined,'prow');foot.append(error,save);
box.append(foot,node('small','Preço e data servem para o retorno da máquina em Números.','sub'));
body.push(node('h4','Dados da máquina','sh'),box);
}
sheetModal=modal('Ficha da '+machine.name,{host:dialogHost(),width:640,body});
}
// The launch form: type, item, and only the fields that type uses. Resolves
// true when the entry was saved, false when the dialog was closed.
async function machineEntryForm(machineId, preset={}, data=null){
if(!data){
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return false;}
}
const catalog=data.catalog;
const kind=node('select');
for(const [value,label] of [['supply','Insumo'],['part','Peça'],['event','Evento']]){
const option=node('option',label);option.value=value;kind.append(option);}
kind.value=preset.kind||'supply';
const item=node('select');
const fillItems=()=>{
const map=kind.value==='supply'?catalog.supplies:kind.value==='part'?catalog.parts:catalog.events;
item.replaceChildren(...Object.entries(map).map(([value,meta])=>{
const option=node('option',Array.isArray(meta)?meta[0]:meta);option.value=value;return option;}));
if(preset.item&&kind.value===(preset.kind||'supply'))item.value=preset.item;
};
fillItems();
const quantity=node('input');quantity.type='number';quantity.min='0.001';quantity.step='0.001';quantity.inputMode='decimal';
const cost=node('input');cost.type='number';cost.min='0';cost.step='0.01';cost.inputMode='decimal';
const serial=node('input');serial.maxLength=200;
const note=node('input');note.maxLength=1000;
const minutes=node('input');minutes.type='number';minutes.min='1';minutes.step='1';
const quantityField=field('Quantidade',quantity,'Unidade: ');
const costField=field('Custo (R$)',cost,'Vazio usa o último custo');
const serialField=field('Número de série',serial);
const noteCaption=node('span','Descrição');
const noteField=node('label',undefined,'fld');noteField.append(noteCaption,note);
const minutesField=field('Minutos parados',minutes);
const quantityHint=quantityField.querySelector('small'),costHint=costField.querySelector('small');
const sync=()=>{
const supply=kind.value==='supply',part=kind.value==='part',event=kind.value==='event';
const stop=event&&item.value==='stop';
quantityField.hidden=!supply;
costField.hidden=!(supply||part);
serialField.hidden=!part;
noteField.hidden=!((part&&item.value==='other')||stop);
minutesField.hidden=!stop;
noteCaption.textContent=stop?'Motivo da parada':'Descrição';
quantityHint.textContent=supply?'Unidade: '+(catalog.supplies[item.value]?.[1]||''):'';
costHint.textContent=supply?'Vazio usa o último custo':'';
};
kind.onchange=()=>{preset.item=null;fillItems();sync();};
item.onchange=sync;
sync();
return new Promise(resolve=>{
let settled=false;
const finish=value=>{if(settled)return;settled=true;resolve(value);};
const error=node('span',undefined,'warn');error.hidden=true;
const dialog=formDialog('Lançar na ficha',{host:dialogHost(),width:560,left:[error],
fields:[field('Tipo',kind),field('Item',item),quantityField,costField,serialField,noteField,minutesField],
label:'Lançar',onsave:async()=>{
try{
const payload={kind:kind.value,item:item.value,from_alert:!!preset.from_alert};
if(kind.value==='supply'){
if(quantity.value.trim()==='')throw new Error('Informe a quantidade que entrou.');
payload.quantity=Number(quantity.value);
payload.cost_cents=cost.value.trim()===''?null:Math.round(Number(cost.value)*100);
}else if(kind.value==='part'){
if(cost.value.trim()==='')throw new Error('Informe o custo da peça.');
payload.cost_cents=Math.round(Number(cost.value)*100);
payload.serial=serial.value.trim()||null;
payload.note=note.value.trim()||null;
}else if(item.value==='stop'){
if(!note.value.trim()||minutes.value.trim()==='')throw new Error('Informe o motivo e os minutos da parada.');
payload.note=note.value.trim();
payload.stop_minutes=Number(minutes.value);
}
await api('/machines/'+machineId+'/entries',payload);
}catch(e){error.textContent=e.message;error.hidden=false;return false;}
finish(true);
}});
const close=dialog.close.bind(dialog);
dialog.close=()=>{close();finish(false);};
});
}
// The alert shown when a card is pulled between one file and the next. Resolves
// true when the alert was resolved or postponed, false when the user backs out.
function machineAlertDialog(order,machineId,alert){
return new Promise(resolve=>{
let decided=false;
const made=node('button','Marcar como feito','btn pri');made.type='button';
const later=node('button','Adiar uma vez','btn');later.type='button';
const back=node('button','Voltar','btn ghost right');back.type='button';
const modalEntry=modal('Antes do próximo arquivo',{text:alert.text,host:dialogHost(),width:520,
role:'alertdialog',foot:[...(alert.snoozable?[later]:[]),back,made],
onclose:()=>{if(!decided)resolve(false);}});
back.onclick=()=>modalEntry.close();
const run=async action=>{
made.disabled=true;later.disabled=true;message.hidden=true;
try{
const proceed=await action();
if(proceed===false)return;
decided=true;modalEntry.close();
await load();
resolve(true);
}catch(e){message.textContent=e.message;message.hidden=false;}
finally{made.disabled=false;later.disabled=false;}
};
const message=node('span',undefined,'warn');message.hidden=true;
modalEntry.box.querySelector('.dfoot')?.prepend(message);
made.onclick=()=>run(async()=>{
if(alert.key.startsWith('supply:')){
return await machineEntryForm(machineId,{kind:'supply',item:alert.key.slice(7),from_alert:true});
}
await api('/machines/'+machineId+'/entries',{kind:'event',item:alert.key,from_alert:true});
return true;
});
later.onclick=()=>run(async()=>{
await api('/machines/'+machineId+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
return true;
});
});
}
// Pulling a card to a machine always passes the sheet's blocking alert first,
// then the server re-checks it under the machine's lock.
async function pullTo(order, machineId){
const target=machineId||order.machine?.id||myMachine()?.id||null;
if(target){
const machine=(board.machines||[]).find(row=>row.id===target);
const alert=(machine?.alerts||[]).find(row=>row.blocking);
if(alert&&!await machineAlertDialog(order,target,alert))return;
}
try{
await move(order,'imp','',target);
}catch(e){
if(e.status===409&&String(e.message).startsWith('Antes do próximo arquivo')){say(e.message,true);return;}
throw e;
}
}
// Minha conta: who is signed in, and the password, which only the person changes.
function accountForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';
const next=node('input');next.type='password';next.required=true;next.minLength=8;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=8;again.autocomplete='new-password';
const dl=node('dl',undefined,'dl');
for(const [k,v] of [['E-mail',ME.email],['Perfil',ROLE_NAMES[ME.role]||ME.role],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){
const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
const sect=node('div',undefined,'sect');
const row=node('div',undefined,'frow');row.append(field('Nova senha',next,'8 caracteres ou mais'),field('Repita a nova senha',again));
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
text:ROLE_NAMES[ME.role]+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
}});
}
$('my-password').onclick=()=>{$('account-menu').hidden=true;accountForm();};
// Dark or light, per browser (web/theme.js): the rail's button and the account
// menu name the one a click gives.
const ICON_SUN='M6.75 10a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M10 2v1.75 M10 16.25V18 M2 10h1.75 M16.25 10H18 M4.35 4.35l1.24 1.24 M14.41 14.41l1.24 1.24 M4.35 15.65l1.24-1.24 M14.41 5.59l1.24-1.24';
const ICON_MOON='M16.25 12.25A6.75 6.75 0 0 1 7.75 3.75a6.75 6.75 0 1 0 8.5 8.5z';
function paintThemeToggle(){
const light=kanbanTheme.get()==='light', label=light?'Mudar para o modo escuro':'Mudar para o modo claro';
$('theme-rail').querySelector('path').setAttribute('d',light?ICON_MOON:ICON_SUN);
$('theme-rail').setAttribute('aria-label',label);$('theme-rail').title=label;
}
$('theme-rail').onclick=()=>{kanbanTheme.toggle();paintThemeToggle();};
paintThemeToggle();
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('filter-btn').onclick=e=>{e.stopPropagation();if($('filter-pop').hidden)openFilters();else closeFilters();};
$('filter-pop').onclick=e=>e.stopPropagation();
$('filter-pop').onkeydown=e=>{if(e.key==='Escape'){e.stopPropagation();closeFilters();$('filter-btn').focus();}};
document.addEventListener('click',()=>{if(!$('filter-pop').hidden)closeFilters();});
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);

View File

@@ -297,4 +297,4 @@
<div class="scrim" id="scrim"></div>
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div>
<script src="/vendor/sentry.min.js"></script><script src="/observability.js"></script><script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
<script src="/vendor/sentry.min.js"></script><script src="/observability.js"></script><script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-quotes.js"></script><script src="/kanban-users.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>

View File

@@ -2471,864 +2471,6 @@ function historyView(order,rows,view){
view.replaceChildren(list);
}
// ---- Machines and users ----------------------------------------------------
// "Em qual máquina você está?" (Dropstar's third round, item 12): after signing
// in, required for the operator, and for Gestão and the administrators with
// "Não estou em máquina". Per session: one person on two computers runs two
// machines. Someone else already on the machine is a warning, not a refusal.
let askingMachine=false;
function askMachine(again=false){
if(!ME?.machine_question||askingMachine||(ME.machine_answered&&!again))return;
askingMachine=true;
const required=ME.machine_question==='required', current=myMachine();
let m=null;
const choose=async(id,confirm=false)=>{
try{await api('/me/machine',{machine_id:id,confirm});m.close();await load(true);}
catch(e){
if(e.status===409&&!confirm&&await ask('Outra pessoa está nesta máquina',e.message,'Continuar mesmo assim'))return choose(id,true);
say(e.message,true);}};
// Each machine with what it is printing, and who is on it now.
const list=node('div',undefined,'mchoices');
for(const machine of (board.machines||[]).filter(x=>x.active)){
const mine=current?.id===machine.id;
const b=node('button',undefined,'mchoice'+(mine?' on':''));b.type='button';b.setAttribute('aria-pressed',String(mine));
const head=node('span',undefined,'mhead');head.append(node('b',machine.name));
if(mine){const tick=node('span',undefined,'tick');tick.append(svgIcon(IC.check,'i s'));head.append(tick);}
b.append(head,node('span',machine.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','sub'));
const here=board.orders.filter(o=>o.state==='imp'&&!o.cancelled_at&&o.machine?.id===machine.id)
.sort((x,y)=>(x.printing==='imprimindo'?0:1)-(y.printing==='imprimindo'?0:1));
for(let i=0;i<Math.max(board.printing_cap||2,here.length);i++){
const o=here[i],job=node('span',undefined,'job');
if(o)job.append(node('i',undefined,o.printing==='ripando'?'ripmark':'runmark'),node('span','#'+o.number,'code'),node('em',o.printing==='ripando'?'ripando':'imprimindo'));
else job.append(node('i',undefined,'freemark'),node('span','livre','free'));
b.append(job);
}
if(machine.operators){const others=machine.operators.filter(op=>op.name!==(ME.name||ME.email));
b.append(node('span',others.length?others.map(op=>op.name).join(', ')+(others.length>1?' estão nela':' está nela'):'Ninguém mais nela','who'));}
b.onclick=()=>choose(machine.id);list.append(b);
}
if(!list.children.length)list.append(node('p','Nenhuma máquina ativa. Peça ao Administrador para cadastrar em Usuários, Máquinas.','empty'));
const foot=[];
if(!required)foot.push(button('Não estou em máquina',()=>choose(null),'btn ghost'));
if(required&&!ME.machine_answered)foot.push(button('Sair',()=>$('logout').click(),'btn ghost'));
if(current&&ME.machine_answered)foot.push(button('Continuar na '+current.name,async()=>m.close(),'btn pri right'));
m=modal('Em qual máquina você está?',{text:'O que você puxar para Imprimindo vai para ela, e o histórico grava a máquina com o seu nome.',
body:[list],foot,width:620,locked:required&&!ME.machine_answered,onclose:()=>{askingMachine=false;}});
}
// The machine beside the account button: green, and a click changes it.
function paintMyMachine(){
const asked=!!ME?.machine_question, mine=myMachine();
for(const id of ['my-machine','rail-machine','account-machine'])$(id).hidden=!asked;
if(!asked)return;
const name=mine?mine.name:'Sem máquina';
const chip=$('my-machine');chip.replaceChildren(node('i'),node('span','Máquina '),node('b',name));
chip.classList.toggle('on',!!mine);
chip.title=mine?'Você está na '+mine.name+'. Clique para trocar.':'Você não está em máquina. Clique para escolher.';
const rail=$('rail-machine');rail.querySelector('b').textContent=mine?mine.name:'Nenhuma';rail.classList.toggle('on',!!mine);rail.title=chip.title;
$('account-machine').querySelector('.lbl').textContent=mine?mine.name:'';
}
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
// The machine is recorded when the card is pulled into Imprimindo.
function machineCard(order){
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
const current=order.machine;
const pulled=order.machine_pulled;
const detail=pulled?'Puxada por '+pulled.by+' em '+when(pulled.at):current?'Escolhida para este pedido':'Definida quando alguém puxar o card';
// The operator's orders go to the machine that pulls them (item 12).
if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail));
return box;
}
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
const auto=node('option','Sem máquina');auto.value='';select.append(auto);
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
}
select.value=current?.id||'';
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'O pedido aguarda uma máquina.');await load();}
catch(e){say(e.message,true);}};
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail),select);
return box;
}
// "120,00 m de 300,00 m" or "120,00 m em aberto".
function machineLoad(m){
return m.limit_metres?metres(m.open_metres)+' de '+metres(m.limit_metres):metres(m.open_metres)+' em aberto';
}
// Chips that switch on and off (what a machine prints): .values() is what is on.
function pills(options,selected){
const box=node('div',undefined,'fopts'),on=new Set(selected);
for(const [value,label] of options){
const b=node('button',label,'fopt'+(on.has(value)?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on.has(value)));
b.onclick=()=>{if(on.has(value))on.delete(value);else on.add(value);b.classList.toggle('on',on.has(value));b.setAttribute('aria-pressed',String(on.has(value)));};
box.append(b);
}
box.values=()=>options.map(([v])=>v).filter(v=>on.has(v));return box;
}
// A dialog field that is a group (chips, a list) rather than one input.
function group(label,...content){const g=node('div',undefined,'fld');g.append(node('span',label),...content);return g;}
// A list to choose from, drawn by us: each choice with a line on what it means.
function choice(options,value,{label,disabled=false}={}){
const wrap=node('div',undefined,'sel');let current=value;
const btn=node('button',undefined,'selbtn');btn.type='button';btn.disabled=disabled;
btn.setAttribute('aria-haspopup','listbox');btn.setAttribute('aria-expanded','false');if(label)btn.setAttribute('aria-label',label);
const text=node('span');btn.append(text,svgIcon(IC.down,'i m'));
const list=node('div',undefined,'pop sellist');list.setAttribute('role','listbox');list.hidden=true;
const hint=node('small');
const close=()=>{list.hidden=true;btn.classList.remove('open');btn.setAttribute('aria-expanded','false');};
const paint=()=>{const o=options.find(x=>x.value===current)||options[0];text.textContent=o.label;hint.textContent=o.hint||'';
for(const b of list.children){const on=b.dataset.value===current;b.setAttribute('aria-selected',String(on));b.querySelector('.ck').replaceChildren(...(on?[svgIcon(IC.check,'i m')]:[]));}};
for(const o of options){
const b=node('button',undefined,'selopt');b.type='button';b.setAttribute('role','option');b.dataset.value=o.value;
const words=node('span');words.append(node('b',o.label),...(o.hint?[node('small',o.hint)]:[]));
b.append(node('span',undefined,'ck'),words);
b.onclick=()=>{current=o.value;paint();close();btn.focus();};list.append(b);
}
btn.onclick=e=>{e.stopPropagation();if(!list.hidden)return close();list.hidden=false;btn.classList.add('open');btn.setAttribute('aria-expanded','true');
list.querySelector('[aria-selected=true]')?.focus();
setTimeout(()=>document.addEventListener('click',close,{once:true}));};
list.onkeydown=e=>{const items=[...list.children],i=items.indexOf(document.activeElement);
if(e.key==='ArrowDown'){e.preventDefault();items[Math.min(items.length-1,i+1)].focus();}
if(e.key==='ArrowUp'){e.preventDefault();items[Math.max(0,i-1)].focus();}};
wrap.append(btn,list);paint();
wrap.value=()=>current;wrap.hint=hint;wrap.close=close;wrap.isOpen=()=>!list.hidden;
return wrap;
}
const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
// What each profile is for, in a line (app/core/auth.py).
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa, libera para Finalizado e reimprime a etiqueta.',
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
expedicao:'Monta folhas no Kanban e imprime a etiqueta; só consulta o resto.'};
// Who is on the system: used it in the last 15 minutes, signed in before,
// never, or switched off.
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
const presence=u=>!u.active?'off':u.seen_at&&Date.now()-new Date(u.seen_at)<15*60e3?'on':u.last_login_at?'away':'never';
const initialsOf=text=>String(text||'').trim().split(/\s+/).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'·';
function avatar(u,className='ava'){
const a=node('span',initialsOf(u.name||u.email),className),p=node('i',undefined,'pres '+presence(u));
p.title=PRESENCE[presence(u)];a.append(p);return a;
}
// "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py).
const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY'],
['Imprimir a etiqueta 10×15','YYNNYNNY']];
let usersData=null;
async function loadUsers(){
usersData=await api('/users');
renderUsers();
}
function renderUsers(){
const {users,machines}=usersData;
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
$('users-count').textContent=String(users.length);
$('users-list').replaceChildren(...users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const who=node('td'),line=node('span',undefined,'who'),words=node('span');
words.append(node('b',u.name||u.email),node('span',u.email,'sub'));line.append(avatar(u),words);who.append(line);
const machine=node('td');
if(u.machines.length){const m=node('span',undefined,'mcell');m.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));machine.append(m);}
else machine.append(node('span','Sem máquina','muted'));
const open=node('td',undefined,'r');
if(editable){open.append(iconButton(IC.right,'Editar '+(u.name||u.email),()=>userForm(u),'btn sq ghost'));tr.classList.add('click');tr.onclick=()=>userForm(u);}
tr.append(who,node('td',ROLE_NAMES[u.role]+(u.active?'':', desativado')),machine,
node('td',u.last_login_at?ago(u.last_login_at):'nunca entrou','muted'),open);
return tr;
}));
// On the phone, a list of people, each a row that opens them.
const list=$('users-phone');list.replaceChildren(...users.map(u=>{
const editable=u.role!=='superadmin'||ME.role==='superadmin';
const row=node('button',undefined,'mli');row.type='button';row.disabled=!editable;if(editable)row.onclick=()=>userForm(u);
const words=node('span',undefined,'grow'),sub=node('span',undefined,'sub mcell');
sub.append(ROLE_NAMES[u.role]+(u.active?'':', desativado'));
if(u.machines.length){sub.append(node('i',undefined,'mdot'),u.machines.map(machineName).join(', '));}
words.append(node('b',u.name||u.email),sub);
row.append(avatar(u),words,svgIcon(IC.right,'i m'));return row;}));
const head=node('tr');head.append(node('th',''));for(const r of ROLE_COLUMNS)head.append(node('th',ROLE_NAMES[r]));
for(const th of head.children)th.scope='col';head.firstChild.append(node('span','Ação','vh'));
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const [label,cells] of ROLE_MATRIX){const tr=node('tr');tr.append(node('td',label));
[...cells].forEach(k=>{const td=node('td'),i=node('i',undefined,k==='Y'?'can':k==='V'?'can view':'can no');
td.title=k==='Y'?'Faz':k==='V'?'Só consulta':'Não';td.append(i,node('span',td.title,'vh'));tr.append(td);});tbody.append(tr);}
$('roles-matrix').replaceChildren(thead,tbody);
$('machines-count').textContent=String(machines.length);
$('machines-list').replaceChildren(...(machines.length?machines.map(machineTile)
:[emptyState(IC.printer,'Nenhuma máquina cadastrada','Cadastre as máquinas para os pedidos irem para elas.')]));
}
// A machine: its metres open against its limit, its orders by stage, and who is on it.
const STAGE_FILL={rec:'var(--tx3)',tra:'var(--ln3)',imp:'var(--ink)',cor:'var(--bad)',rev:'var(--tx2)'};
function machineTile(m){
const tile=node('article',undefined,'mtile'+(m.active?'':' off'));
const head=node('div',undefined,'row');
head.append(node('h3',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','lbl'));
if(!m.active)head.append(badge('Desativada',''));
head.append(button('Ficha',()=>openMachineSheet(m.id),'btn ghost right'),button('Editar',()=>machineForm(m),'btn ghost'));
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const load=node('div',undefined,'row base');
load.append(node('b',metres(m.open_metres),over?'bad':''),node('span','em aberto, '+(m.limit_metres?'limite de '+metres(m.limit_metres)+(over?', acima do limite':''):'sem limite'),'lbl'));
const stages=Object.keys(STAGE_FILL).filter(s=>m.states[s]);
const total=stages.reduce((t,s)=>t+m.states[s],0);
tile.append(head,load);
if(total){
const stack=node('div',undefined,'stack'),list=node('ul');
for(const s of stages){const seg=node('i');seg.style.width=(100*m.states[s]/total)+'%';seg.style.background=STAGE_FILL[s];stack.append(seg);
const li=node('li'),dot=node('i');dot.style.background=STAGE_FILL[s];li.append(dot,board?.states?.[s]||s,node('b',String(m.states[s])));list.append(li);}
tile.append(stack,list);
}else tile.append(node('span','Nenhum pedido em aberto','lbl'));
const people=node('div',undefined,'row people');people.append(svgIcon(IC.user,'i s'),
m.operators?.length?m.operators.map(o=>o.name+(o.since?' desde '+new Date(o.since).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'')).join(', ')+(m.operators.length>1?' estão nela':' está nela'):'Ninguém nela agora');
tile.append(people);
return tile;
}
function userForm(u){
const editing=!!u;
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome';
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br';
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'];
const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador',
{label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email});
const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint);
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter a atual':'8 caracteres ou mais';
const active=node('input');active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const row=node('div',undefined,'frow');row.append(field('Nome',name),field('E-mail',email));
const left=[];
if(editing&&u.email!==ME.email){
const remove=node('button','Excluir usuário','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir '+(u.name||u.email)+'?','A pessoa não entra mais no sistema. Os pedidos continuam com o nome dela no histórico. Para só bloquear o acesso, desmarque Ativo.','Excluir usuário',{tone:'red'}))return;
try{await api('/users/'+u.id+'/delete',{});m.close();say('Usuário excluído.');await loadUsers();}catch(e){say(e.message,true);}};
left.push(remove);
}
const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null,
text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.',
fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),checkbox('Ativo: pode entrar no sistema',active)],
label:editing?'Salvar':'Criar usuário',onsave:async()=>{
const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers();
}});
}
function machineForm(m){
const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';name.placeholder='Ex.: Têxtil 2';
const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]);
const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal';
limit.placeholder='Sem limite';limit.value=m?.limit_metres??'';
const active=node('input');active.checked=m?m.active:true;
const left=[];
if(m){
const remove=node('button','Excluir máquina','btn quiet');remove.type='button';
remove.onclick=async()=>{
if(!await ask('Excluir a máquina '+m.name+'?','Os pedidos dela vão para outra máquina do produto.','Excluir máquina',{tone:'red'}))return;
try{await api('/machines/'+m.id+'/delete',{});d.close();say('Máquina excluída.');await loadUsers();await load();}catch(e){say(e.message,true);}};
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
checkbox('Ativa: recebe pedidos',active)],
onsave:async()=>{
if(!products.values().length)throw new Error('Marque o que a máquina imprime.');
await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(),
limit_metres:limit.value?Number(limit.value):null});
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
}});
}
// ---- Machine sheet (Fase 2, front 1a) --------------------------------------
//
// What goes into a machine, what the room has printed since the last clean and
// the last film roll, and the alerts that wait between one file and the next.
// The numbers per machine (cost, ROI) are part b and stay in Números.
function machineEntryLine(entry, catalog){
const label=entry.label||entry.item;
let detail='';
if(entry.kind==='supply'){
const unit=catalog.supplies[entry.item]?.[1]||'';
detail=Number(entry.quantity).toLocaleString('pt-BR',{maximumFractionDigits:3})+' '+unit;
if(entry.cost_cents!==null&&entry.cost_cents!==undefined)detail+=' · '+money(entry.cost_cents);
}else if(entry.kind==='part'){
detail=(entry.note?entry.note+' · ':'')+(entry.serial?'série '+entry.serial+' · ':'')+money(entry.cost_cents);
}else if(entry.item==='stop'){
detail=entry.stop_minutes+' min'+(entry.note?' · '+entry.note:'');
}
return [when(entry.created_at),label,detail,entry.created_by].filter(Boolean).join(' · ');
}
async function openMachineSheet(machineId){
let data;
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return;}
const machine=data.machine;
const launch=may('print')&&(ME?.role!=='operador'||myMachine()?.id===machine.id);
const body=[];
let sheetModal=null;
const refresh=async()=>{sheetModal?.close();await load();openMachineSheet(machine.id);};
const minimum=value=>Number(value).toLocaleString('pt-BR',{maximumFractionDigits:3});
const counts=node('div',undefined,'mblock');
const fact=(label,value)=>{const row=node('div',undefined,'mfact');row.append(node('span',label),node('b',value));counts.append(row);};
const clean=data.counters.clean, film=data.counters.film;
fact('Desde a última limpeza',m1(clean.metres)+' m'+(clean.since?'':' (nenhuma limpeza lançada ainda)'));
fact('Desde a troca de filme',film.since?m1(film.metres)+' m '+(film.aligned?'(cabeça alinhada)':'(falta alinhar)'):'sem registro');
body.push(node('h4','Contadores','sh'),counts);
const supplies=node('div',undefined,'mblock');
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const value=data.supplies[item];
const row=node('div',undefined,'mfact');
let text;
if(value){
text='acaba em ~'+m1(value.metres_left)+' m';
if(value.minimum!==null&&value.minimum!==undefined)text+=' · mínimo '+minimum(value.minimum)+' '+unit;
}else text='lance duas reposições para estimar';
row.append(node('span',label),node('b',text));
supplies.append(row);
}
body.push(node('h4','Insumos','sh'),supplies);
if(data.alerts.length){
const box=node('div',undefined,'mblock');
const done=async alert=>{
if(alert.key.startsWith('supply:')){
const saved=await machineEntryForm(machine.id,{kind:'supply',item:alert.key.slice(7),from_alert:true},data);
if(!saved)return;
}else{
await api('/machines/'+machine.id+'/entries',{kind:'event',item:alert.key,from_alert:true});
}
say('Aviso resolvido.');
await refresh();
};
for(const alert of data.alerts){
const row=node('div',undefined,'sheetalert');
const words=node('span',undefined,'grow');
words.append(node('b',alert.text),node('span',alert.blocking?'pendente':'adiado neste ciclo','sub'));
row.append(words);
if(launch){
const actions=node('span',undefined,'prow');
actions.append(button('Marcar como feito',()=>done(alert),'btn'));
if(alert.snoozable)actions.append(button('Adiar uma vez',async()=>{
await api('/machines/'+machine.id+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
say('Aviso adiado: passa um arquivo e ele volta.');
await refresh();
},'btn ghost'));
row.append(actions);
}
box.append(row);
}
body.push(node('h4','Avisos pendentes','sh'),box);
}
const entries=node('div',undefined,'mlist sheetentries');
if(data.entries.length)for(const entry of data.entries)entries.append(node('div',machineEntryLine(entry,data.catalog),'mli'));
else entries.append(node('div','Nenhum lançamento ainda','mli muted'));
body.push(node('h4','Lançamentos','sh'),entries);
if(launch){
const prow=node('div',undefined,'prow');
prow.append(button('Lançar',async()=>{
const saved=await machineEntryForm(machine.id,{},data);
if(!saved)return;
say('Lançamento registrado.');
await refresh();
},'btn pri'));
body.push(prow);
}
if(may('manage')){
const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal';
price.value=data.machine.price_cents!==null&&data.machine.price_cents!==undefined?(data.machine.price_cents/100).toFixed(2):'';
const installed=node('input');installed.type='date';installed.value=data.machine.installed_on||'';
const minimums={};
const box=node('div',undefined,'mblock');
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
// Dropstar's fixed minimums are the defaults: a machine with none typed
// shows and uses them until Gestão changes them.
const typed=data.minimums[item], fallback=data.default_minimums?.[item];
input.value=typed!==null&&typed!==undefined?Number(typed).toString()
:fallback!==null&&fallback!==undefined?Number(fallback).toString():'';
minimums[item]=input;
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
}
const error=node('span',undefined,'warn');error.hidden=true;
const save=node('button','Salvar','btn pri');save.type='button';
save.onclick=async()=>{
save.disabled=true;error.hidden=true;
try{
await api('/machines/'+machine.id+'/sheet',{
price_cents:price.value.trim()===''?null:Math.round(Number(price.value)*100),
installed_on:installed.value||null,
minimums:Object.fromEntries(Object.entries(minimums).map(([item,input])=>
[item,input.value.trim()===''?null:Number(input.value)]))});
say('Dados da máquina salvos.');
await refresh();
}catch(e){error.textContent=e.message;error.hidden=false;}
finally{save.disabled=false;}
};
const foot=node('div',undefined,'prow');foot.append(error,save);
box.append(foot,node('small','Preço e data servem para o retorno da máquina em Números.','sub'));
body.push(node('h4','Dados da máquina','sh'),box);
}
sheetModal=modal('Ficha da '+machine.name,{host:dialogHost(),width:640,body});
}
// The launch form: type, item, and only the fields that type uses. Resolves
// true when the entry was saved, false when the dialog was closed.
async function machineEntryForm(machineId, preset={}, data=null){
if(!data){
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return false;}
}
const catalog=data.catalog;
const kind=node('select');
for(const [value,label] of [['supply','Insumo'],['part','Peça'],['event','Evento']]){
const option=node('option',label);option.value=value;kind.append(option);}
kind.value=preset.kind||'supply';
const item=node('select');
const fillItems=()=>{
const map=kind.value==='supply'?catalog.supplies:kind.value==='part'?catalog.parts:catalog.events;
item.replaceChildren(...Object.entries(map).map(([value,meta])=>{
const option=node('option',Array.isArray(meta)?meta[0]:meta);option.value=value;return option;}));
if(preset.item&&kind.value===(preset.kind||'supply'))item.value=preset.item;
};
fillItems();
const quantity=node('input');quantity.type='number';quantity.min='0.001';quantity.step='0.001';quantity.inputMode='decimal';
const cost=node('input');cost.type='number';cost.min='0';cost.step='0.01';cost.inputMode='decimal';
const serial=node('input');serial.maxLength=200;
const note=node('input');note.maxLength=1000;
const minutes=node('input');minutes.type='number';minutes.min='1';minutes.step='1';
const quantityField=field('Quantidade',quantity,'Unidade: ');
const costField=field('Custo (R$)',cost,'Vazio usa o último custo');
const serialField=field('Número de série',serial);
const noteCaption=node('span','Descrição');
const noteField=node('label',undefined,'fld');noteField.append(noteCaption,note);
const minutesField=field('Minutos parados',minutes);
const quantityHint=quantityField.querySelector('small'),costHint=costField.querySelector('small');
const sync=()=>{
const supply=kind.value==='supply',part=kind.value==='part',event=kind.value==='event';
const stop=event&&item.value==='stop';
quantityField.hidden=!supply;
costField.hidden=!(supply||part);
serialField.hidden=!part;
noteField.hidden=!((part&&item.value==='other')||stop);
minutesField.hidden=!stop;
noteCaption.textContent=stop?'Motivo da parada':'Descrição';
quantityHint.textContent=supply?'Unidade: '+(catalog.supplies[item.value]?.[1]||''):'';
costHint.textContent=supply?'Vazio usa o último custo':'';
};
kind.onchange=()=>{preset.item=null;fillItems();sync();};
item.onchange=sync;
sync();
return new Promise(resolve=>{
let settled=false;
const finish=value=>{if(settled)return;settled=true;resolve(value);};
const error=node('span',undefined,'warn');error.hidden=true;
const dialog=formDialog('Lançar na ficha',{host:dialogHost(),width:560,left:[error],
fields:[field('Tipo',kind),field('Item',item),quantityField,costField,serialField,noteField,minutesField],
label:'Lançar',onsave:async()=>{
try{
const payload={kind:kind.value,item:item.value,from_alert:!!preset.from_alert};
if(kind.value==='supply'){
if(quantity.value.trim()==='')throw new Error('Informe a quantidade que entrou.');
payload.quantity=Number(quantity.value);
payload.cost_cents=cost.value.trim()===''?null:Math.round(Number(cost.value)*100);
}else if(kind.value==='part'){
if(cost.value.trim()==='')throw new Error('Informe o custo da peça.');
payload.cost_cents=Math.round(Number(cost.value)*100);
payload.serial=serial.value.trim()||null;
payload.note=note.value.trim()||null;
}else if(item.value==='stop'){
if(!note.value.trim()||minutes.value.trim()==='')throw new Error('Informe o motivo e os minutos da parada.');
payload.note=note.value.trim();
payload.stop_minutes=Number(minutes.value);
}
await api('/machines/'+machineId+'/entries',payload);
}catch(e){error.textContent=e.message;error.hidden=false;return false;}
finish(true);
}});
const close=dialog.close.bind(dialog);
dialog.close=()=>{close();finish(false);};
});
}
// The alert shown when a card is pulled between one file and the next. Resolves
// true when the alert was resolved or postponed, false when the user backs out.
function machineAlertDialog(order,machineId,alert){
return new Promise(resolve=>{
let decided=false;
const made=node('button','Marcar como feito','btn pri');made.type='button';
const later=node('button','Adiar uma vez','btn');later.type='button';
const back=node('button','Voltar','btn ghost right');back.type='button';
const modalEntry=modal('Antes do próximo arquivo',{text:alert.text,host:dialogHost(),width:520,
role:'alertdialog',foot:[...(alert.snoozable?[later]:[]),back,made],
onclose:()=>{if(!decided)resolve(false);}});
back.onclick=()=>modalEntry.close();
const run=async action=>{
made.disabled=true;later.disabled=true;message.hidden=true;
try{
const proceed=await action();
if(proceed===false)return;
decided=true;modalEntry.close();
await load();
resolve(true);
}catch(e){message.textContent=e.message;message.hidden=false;}
finally{made.disabled=false;later.disabled=false;}
};
const message=node('span',undefined,'warn');message.hidden=true;
modalEntry.box.querySelector('.dfoot')?.prepend(message);
made.onclick=()=>run(async()=>{
if(alert.key.startsWith('supply:')){
return await machineEntryForm(machineId,{kind:'supply',item:alert.key.slice(7),from_alert:true});
}
await api('/machines/'+machineId+'/entries',{kind:'event',item:alert.key,from_alert:true});
return true;
});
later.onclick=()=>run(async()=>{
await api('/machines/'+machineId+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
return true;
});
});
}
// Pulling a card to a machine always passes the sheet's blocking alert first,
// then the server re-checks it under the machine's lock.
async function pullTo(order, machineId){
const target=machineId||order.machine?.id||myMachine()?.id||null;
if(target){
const machine=(board.machines||[]).find(row=>row.id===target);
const alert=(machine?.alerts||[]).find(row=>row.blocking);
if(alert&&!await machineAlertDialog(order,target,alert))return;
}
try{
await move(order,'imp','',target);
}catch(e){
if(e.status===409&&String(e.message).startsWith('Antes do próximo arquivo')){say(e.message,true);return;}
throw e;
}
}
// Minha conta: who is signed in, and the password, which only the person changes.
function accountForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';
const next=node('input');next.type='password';next.required=true;next.minLength=8;next.autocomplete='new-password';
const again=node('input');again.type='password';again.required=true;again.minLength=8;again.autocomplete='new-password';
const dl=node('dl',undefined,'dl');
for(const [k,v] of [['E-mail',ME.email],['Perfil',ROLE_NAMES[ME.role]||ME.role],...(ME.machine_question?[['Máquina agora',myMachine()?.name||'Nenhuma']]:[])]){
const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
const sect=node('div',undefined,'sect');
const row=node('div',undefined,'frow');row.append(field('Nova senha',next,'8 caracteres ou mais'),field('Repita a nova senha',again));
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
text:ROLE_NAMES[ME.role]+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
}});
}
$('my-password').onclick=()=>{$('account-menu').hidden=true;accountForm();};
// Dark or light, per browser (web/theme.js): the rail's button and the account
// menu name the one a click gives.
const ICON_SUN='M6.75 10a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M10 2v1.75 M10 16.25V18 M2 10h1.75 M16.25 10H18 M4.35 4.35l1.24 1.24 M14.41 14.41l1.24 1.24 M4.35 15.65l1.24-1.24 M14.41 5.59l1.24-1.24';
const ICON_MOON='M16.25 12.25A6.75 6.75 0 0 1 7.75 3.75a6.75 6.75 0 1 0 8.5 8.5z';
function paintThemeToggle(){
const light=kanbanTheme.get()==='light', label=light?'Mudar para o modo escuro':'Mudar para o modo claro';
$('theme-rail').querySelector('path').setAttribute('d',light?ICON_MOON:ICON_SUN);
$('theme-rail').setAttribute('aria-label',label);$('theme-rail').title=label;
}
$('theme-rail').onclick=()=>{kanbanTheme.toggle();paintThemeToggle();};
paintThemeToggle();
$('account').onclick=e=>{e.stopPropagation();const m=$('account-menu');m.hidden=!m.hidden;
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;},{once:true});};
$('filter-btn').onclick=e=>{e.stopPropagation();if($('filter-pop').hidden)openFilters();else closeFilters();};
$('filter-pop').onclick=e=>e.stopPropagation();
$('filter-pop').onkeydown=e=>{if(e.key==='Escape'){e.stopPropagation();closeFilters();$('filter-btn').focus();}};
document.addEventListener('click',()=>{if(!$('filter-pop').hidden)closeFilters();});
$('new-user').onclick=()=>userForm(null);
$('new-machine').onclick=()=>machineForm(null);
// ---- 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)':'';
// ---- Payments and integrations ------------------------------------------