All checks were successful
Build and deploy / Validate source (push) Successful in 1m11s
Build and deploy / Integration suite on a real stack (push) Successful in 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m24s
An order in Arte tratada without an approved final showed "Mover para Fila de impressão" as its main button, which the server refused, while the approval sat folded at the bottom of the panel. Now the top of the panel says what comes next: approve the final, with the file that would be printed and a link to download it. A customer's correction or the generated PDF is approved with one click; otherwise the upload form opens in place. Once approved, the main button becomes the move to the queue. A customer's correction can be approved as the final itself, without downloading and sending it back. The board carries each order's approved items and corrections, so cards say "Falta aprovar o final", "Correção recebida" or "Final aprovado", and the item card shows the correction instead of the stale reason the generated file could not be made. Going back a stage is a small link, and cancelling or deleting a test order moved into a "⋯" menu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1246 lines
81 KiB
JavaScript
1246 lines
81 KiB
JavaScript
/* Kanban DTF: production board, quote review, payments and integrations.
|
||
Everything is built with textContent; nothing from an order or a customer is
|
||
ever parsed as HTML. The previous screen is in git tag ui-v1. */
|
||
const $ = id=>document.getElementById(id);
|
||
// Remove credentials saved by older local builds. Only HttpOnly sessions now.
|
||
sessionStorage.removeItem('dtf-operator');
|
||
|
||
const STAGE_COLORS={rec:'var(--rec)',tra:'var(--tra)',fil:'var(--fil)',imp:'var(--imp)',cor:'var(--cor)',fin:'var(--fin)'};
|
||
const FLOW=['rec','tra','fil','imp','fin'];
|
||
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
||
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'};
|
||
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto'};
|
||
const LATE_HOURS=4;
|
||
// Payment outcomes are recorded by the API in English; operators read Portuguese.
|
||
function outcomeText(outcome){
|
||
const rules=[
|
||
[/^refused: paid (\S+) but quote total is (\d+)/,m=>'valor pago ('+(m[1]==='None'?'não informado':money(Number(m[1])))+') diferente do total da cotação ('+money(Number(m[2]))+')'],
|
||
[/^refused: quote expired/,()=>'a cotação venceu antes do pagamento'],
|
||
[/^refused: quote not found/,()=>'cotação não encontrada'],
|
||
[/^refused: quote was discarded/,()=>'a cotação tinha sido descartada no Kanban'],
|
||
[/^refused: reference is not a quote id/,()=>'a referência do pagamento não é uma cotação'],
|
||
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
|
||
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
|
||
[/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]],
|
||
];
|
||
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
|
||
return outcome;
|
||
}
|
||
|
||
let board=null;
|
||
let tab='board', filter='all', openOrder=null, openToken=0;
|
||
let quoteKind='pending', pickedQuote=null;
|
||
let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=null;
|
||
// Uploads that have an artwork picture (the customer's browser made it). Every
|
||
// list the API returns says which, so only pictures that exist are asked for.
|
||
const THUMBS=new Set();
|
||
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));return r;};
|
||
let olderFinished=[], finishedMore=null;
|
||
|
||
const money=cents=>(cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
|
||
const metres=value=>Number(value).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m';
|
||
const when=value=>new Date(value).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
function ago(value){
|
||
const minutes=Math.max(0,Math.round((Date.now()-new Date(value))/60000));
|
||
if(minutes<60)return 'há '+minutes+' min';
|
||
const hours=Math.round(minutes/60);
|
||
return hours<48?'há '+hours+' h':'há '+Math.round(hours/24)+' dias';
|
||
}
|
||
// The customer's WhatsApp opens the conversation, for messages the system does
|
||
// not send (a correction, a question about the artwork).
|
||
function whatsappLink(zap){
|
||
const digits=String(zap||'').replace(/\D/g,'');
|
||
if(digits.length<10)return null;
|
||
return 'https://wa.me/'+(digits.length<=11?'55':'')+digits;
|
||
}
|
||
function node(tag,text,className){const e=document.createElement(tag);if(text!==undefined&&text!==null)e.textContent=text;if(className)e.className=className;return e;}
|
||
function button(text,fn,className='btn'){
|
||
const b=node('button',text,className);b.type='button';
|
||
b.onclick=async event=>{event.stopPropagation();b.disabled=true;try{await fn();}catch(e){say(e.message,true);}finally{b.disabled=false;}};
|
||
return b;
|
||
}
|
||
// Messages are notifications, not state: they clear themselves. Errors stay
|
||
// longer so they can be read; a caller can hold one for as long as it needs.
|
||
let sayTimer=null;
|
||
function say(text,error=false,ms){
|
||
clearTimeout(sayTimer);
|
||
for(const id of ['status','login-status']){$(id).textContent=text||'';$(id).classList.toggle('error',!!error);}
|
||
if(text)sayTimer=setTimeout(()=>say(''),ms??(error?8000:4000));
|
||
}
|
||
function icon(path){
|
||
const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');
|
||
svg.setAttribute('width','14');svg.setAttribute('height','14');svg.setAttribute('viewBox','0 0 24 24');
|
||
svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','2.2');svg.setAttribute('aria-hidden','true');
|
||
for(const d of path){const p=document.createElementNS(ns,d.startsWith('circle')?'circle':'path');
|
||
if(d.startsWith('circle')){const [cx,cy,r]=d.split(' ').slice(1);p.setAttribute('cx',cx);p.setAttribute('cy',cy);p.setAttribute('r',r);}else p.setAttribute('d',d);svg.append(p);}
|
||
return svg;
|
||
}
|
||
const ICON_OK=['M5 12l4 4 10-10'], ICON_WARN=['M12 8v5M12 17h.01','circle 12 12 9'];
|
||
// Lucide shapes (ISC licence), in the same stroke as the two above.
|
||
const ICON_TRUCK=['M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2','M15 18H9',
|
||
'M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14','circle 17 18 2','circle 7 18 2'];
|
||
const ICON_PIN=['M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0','circle 12 10 3'];
|
||
const ICON_DOWNLOAD=['M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4','m7 10 5 5 5-5','M12 15V3'];
|
||
const ICON_CHAT=['M7.9 20A9 9 0 1 0 4 16.1L2 22Z'];
|
||
const ICON_COPY=['M9 9h12v12H9z','M5 15V5a2 2 0 0 1 2-2h10'];
|
||
|
||
// ---- Badges: one system on every screen (canvas "Kanban DTF — redesign", v2) --
|
||
// The grade pill is coloured by the price ladder's bands (90/75/60/40), the
|
||
// same for all four products; product, status and warnings are pills with text.
|
||
const GRADE_BANDS=[[90,'g90'],[75,'g75'],[60,'g60'],[40,'g40'],[0,'g0']];
|
||
function gradePill(grade){
|
||
const n=grade===null||grade===undefined||grade===''?NaN:Number(grade);
|
||
const ok=Number.isFinite(n);
|
||
const b=node('span',ok?String(n):'—','grade '+(ok?GRADE_BANDS.find(([min])=>n>=min)[1]:'gnone'));
|
||
b.title=ok?'Nota da arte: '+n:'Sem nota: conferência manual';return b;
|
||
}
|
||
const lowestGrade=items=>{const g=items.map(i=>Number(i.grade)).filter(Number.isFinite);return g.length?Math.min(...g):null;};
|
||
const PRODUCT_BADGE={file:'Têxtil · Folha',avulsa:'Têxtil · Avulsa',uvfile:'UV · Folha',uv:'UV · Avulsa'};
|
||
function productBadge(items){
|
||
const counts=new Map();for(const i of items)counts.set(i.mode,(counts.get(i.mode)||0)+1);
|
||
const [mode,n]=[...counts][0]||['file',0];
|
||
return node('span',PRODUCT_BADGE[mode]+(n>1?' ×'+n:'')+(counts.size>1?' +'+(counts.size-1):''),'pbadge'+(mode.startsWith('uv')?' uv':''));
|
||
}
|
||
function badge(text,tone='',title=''){const b=node('span',text,'pill '+tone);if(title)b.title=title;return b;}
|
||
function place(dest,prefix=''){
|
||
const s=node('span',undefined,'place');s.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?prefix+dest.city+'/'+dest.state:'Retirada em Franca');return s;
|
||
}
|
||
const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1});
|
||
const plural=(n,one,many)=>n+' '+(n===1?one:many);
|
||
function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):String(value||'');}
|
||
function copyButton(text,label){
|
||
const b=node('button',undefined,'copy');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(icon(ICON_COPY));
|
||
b.onclick=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(text);say('Copiado.');}catch(_){say('Não foi possível copiar.',true);}};
|
||
return b;
|
||
}
|
||
// Facts as a grid of small labelled boxes; empty values are left out.
|
||
function facts(pairs){
|
||
const dl=node('dl',undefined,'factgrid');
|
||
for(const [k,v] of pairs){if(v===null||v===undefined||v==='')continue;const d=node('div');d.append(node('dt',k),node('dd',v));dl.append(d);}
|
||
return dl;
|
||
}
|
||
// Who is buying: a name when the order has one (the customer's, or whoever
|
||
// receives the delivery), else the e-mail. With a name, the e-mail is the
|
||
// second line, still searchable.
|
||
function buyer(content){
|
||
const c=content.customer||{}, name=(c.name||content.destination?.recipient||'').trim();
|
||
return {title:name||c.mail, mail:name?c.mail:''};
|
||
}
|
||
function buyerBlock(content,className){
|
||
const who=buyer(content);
|
||
const box=node('div',undefined,'buyer '+(className||''));
|
||
const title=node('b',who.title);title.title=who.mail||who.title;box.append(title);
|
||
if(who.mail)box.append(node('span',who.mail,'buyer-mail'));
|
||
return box;
|
||
}
|
||
// The quote's latest payment attempt as a badge; none means nobody tried yet.
|
||
function paymentBadge(p){
|
||
if(!p)return null;
|
||
const hour=v=>new Date(v).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
|
||
const tried=' · tentativa '+when(p.created_at);
|
||
if(p.method==='pix'){
|
||
if(p.status==='approved')return badge('✓ PIX pago','ok');
|
||
const live=p.status==='pending'&&p.expires_at&&new Date(p.expires_at)>Date.now();
|
||
return live?badge('PIX gerado · expira '+hour(p.expires_at),'info','O cliente gerou o código'+tried)
|
||
:badge('! PIX expirou sem pagamento','warn','O código venceu e o cliente ainda pode gerar outro'+tried);
|
||
}
|
||
if(p.status==='approved')return badge('✓ Cartão aprovado','ok');
|
||
if(p.status==='rejected')return badge('! Cartão recusado','bad',(p.status_detail?'Motivo: '+p.status_detail:'Recusado')+tried);
|
||
if(p.status==='pending')return badge(p.status_detail==='pending_challenge'?'Cartão aguardando o banco':'Cartão em análise','info',tried.slice(3));
|
||
return badge('Pagamento '+p.status,'',tried.slice(3));
|
||
}
|
||
// What the customer calls the order (the id's first 8 characters, as the
|
||
// server's order_code); the # number is the operators'.
|
||
const orderCode=id=>String(id).replace(/-/g,'').slice(0,8).toUpperCase();
|
||
const sheetSize=p=>p?cm(p.film_width_cm)+' × '+cm(p.height_cm)+' cm':null;
|
||
const hoursSince=v=>Math.floor((Date.now()-new Date(v))/3600000);
|
||
// The freight's weight: what the package weighs and, when Jadlog charges the
|
||
// box's size instead (the cubed weight), what it is charged as.
|
||
function freightWeight(fr){
|
||
const kg=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:2})+' kg';
|
||
if(!fr?.weight_kg)return '';
|
||
if(fr.real_kg&&Number(fr.real_kg)<Number(fr.weight_kg))return kg(fr.real_kg)+' · cobrado como '+kg(fr.weight_kg)+' pela caixa';
|
||
return kg(fr.weight_kg);
|
||
}
|
||
// A download button: the arrow, then its label.
|
||
function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(icon(ICON_DOWNLOAD));b.classList.add('with-icon');return b;}
|
||
async function api(path,body){
|
||
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
||
const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');error.status=r.status;throw error;}return d;
|
||
}
|
||
function download(uid){return async()=>{
|
||
const result=await api('/uploads/'+uid+'/download');
|
||
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
||
};}
|
||
function manifest(production){
|
||
const url=URL.createObjectURL(new Blob([JSON.stringify(production,null,2)],{type:'application/json'}));
|
||
const link=node('a');link.href=url;link.download='dtf-layout-'+production.sources[0].upload_id.slice(0,8)+'.json';
|
||
link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||
}
|
||
|
||
// ---- Artwork pictures -------------------------------------------------------
|
||
|
||
// The picture of one upload, or null when the browser could not make one (a
|
||
// CDR, a PSD, an order from before pictures existed).
|
||
function artPicture(uid,alt=''){
|
||
if(!uid||!THUMBS.has(String(uid)))return null;
|
||
const img=node('img');img.src='/api/operator/uploads/'+uid+'/thumbnail';img.alt=alt;img.loading='lazy';img.decoding='async';
|
||
img.onerror=()=>{THUMBS.delete(String(uid));img.remove();};
|
||
return img;
|
||
}
|
||
// A small box with the first picture of these items; without one, the layout
|
||
// drawing, as before pictures existed.
|
||
function artBox(items,className){
|
||
const box=node('div',undefined,'art '+className);
|
||
const uid=items.flatMap(i=>i.uploads||[]).find(u=>THUMBS.has(String(u)));
|
||
const pic=artPicture(uid);
|
||
if(pic){box.append(pic);return box;}
|
||
const item=items.find(i=>i.production?.placements);
|
||
if(item){box.classList.add('layout');box.append(layoutPreview(item.production));}
|
||
else{box.classList.add('none');box.append(node('span','sem prévia','noart'));}
|
||
return box;
|
||
}
|
||
// An item's artwork (each file's picture) and its layout on the film, as two views.
|
||
function itemPreview(item){
|
||
const wrap=node('div',undefined,'preview');
|
||
const pics=(item.uploads||[]).map((uid,i)=>artPicture(uid,'Arte '+(i+1))).filter(Boolean);
|
||
const layout=item.production?.placements?layoutPreview(item.production):null;
|
||
if(!pics.length){if(layout)wrap.append(layout);return wrap;}
|
||
wrap.classList.add('with-art');
|
||
const art=node('div',undefined,'view art');art.append(...pics);
|
||
if(!layout){wrap.append(art);return wrap;}
|
||
const film=node('div',undefined,'view layout');film.append(layout);film.hidden=true;
|
||
const tabs=node('div',undefined,'ptabs');
|
||
const pick=(show)=>{art.hidden=show!=='art';film.hidden=show!=='film';
|
||
for(const b of tabs.children)b.setAttribute('aria-pressed',String(b.dataset.view===show));};
|
||
for(const [view,label] of [['art','Arte'],['film','Montagem no filme']]){
|
||
const b=node('button',label);b.type='button';b.dataset.view=view;b.setAttribute('aria-pressed',String(view==='art'));
|
||
b.onclick=e=>{e.stopPropagation();pick(view);};tabs.append(b);}
|
||
wrap.append(tabs,art,film);return wrap;
|
||
}
|
||
|
||
// ---- Loading and tabs ------------------------------------------------------
|
||
|
||
// What the last load saw, so the next one can tell what is new.
|
||
let seenOrders=null, seenPending=null, unseen=0;
|
||
async function load(quiet=false){
|
||
try{
|
||
board=absorb(await api('/board'));
|
||
noticeNew(quiet);
|
||
const known=new Set(board.orders.map(o=>o.id));
|
||
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
|
||
if(finishedMore===null)finishedMore=board.finished_total>board.finished_shown;
|
||
$('login').hidden=true;$('app').hidden=false;
|
||
if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500);
|
||
render();
|
||
}catch(e){
|
||
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
|
||
// Not being signed in yet is the normal start, not an error.
|
||
if(e.status===401){say('');return;}
|
||
say(e.message,true);
|
||
}
|
||
}
|
||
function showTab(name){
|
||
tab=name;
|
||
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
|
||
for(const id of ['board','quotes','payments','integrations'])$('tab-'+id).hidden=name!==id;
|
||
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
|
||
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
|
||
}
|
||
function render(){
|
||
$('who').textContent=board.operator||'';
|
||
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
|
||
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
|
||
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
|
||
tinyHeader();renderBoard();renderIntegrations();
|
||
// Lists live on their own pages of the API; refresh the one being looked at.
|
||
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
|
||
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
|
||
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
|
||
}
|
||
|
||
// ---- Production board ----------------------------------------------------
|
||
|
||
function printState(order){
|
||
if(order.state==='fil'||order.state==='imp')return {text:'Final aprovado',tone:'ok'};
|
||
if(order.state==='fin')return {text:'Concluído',tone:'ok'};
|
||
if(order.state==='cor')return {text:'Aguardando o cliente',tone:''};
|
||
if(finalDone(order))return {text:'Final aprovado',tone:'ok'};
|
||
if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'};
|
||
const rows=order.print_files||[], items=order.snapshot.items.length;
|
||
const ready=rows.filter(r=>r.status==='ready').length;
|
||
if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''};
|
||
if(ready===items)return {text:'Falta aprovar o final',tone:'warn'};
|
||
if(rows.some(r=>r.status==='manual'||r.status==='failed'))
|
||
return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'};
|
||
return {text:'Sem arquivo gerado',tone:'warn'};
|
||
}
|
||
const stalled=order=>['rec','tra','fil','imp'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000;
|
||
function matchesFilter(order,key){
|
||
// A cancelled order shows only under "Cancelados", and only there.
|
||
if(key==='cancelados')return !!order.cancelled_at;
|
||
if(order.cancelled_at)return false;
|
||
const modes=order.snapshot.items.map(i=>i.mode);
|
||
if(key==='textil')return modes.some(m=>m==='file'||m==='avulsa');
|
||
if(key==='uv')return modes.some(m=>m==='uvfile'||m==='uv');
|
||
if(key==='entrega')return !!order.snapshot.destination;
|
||
if(key==='retirada')return !order.snapshot.destination;
|
||
if(key==='parados')return stalled(order);
|
||
if(key==='manual')return ['rec','tra'].includes(order.state)&&!finalDone(order)&&(order.print_files||[]).some(r=>
|
||
(r.status==='manual'||r.status==='failed')&&!(order.corrections||[]).some(f=>f.item_index===r.item_index));
|
||
return true;
|
||
}
|
||
const matches=order=>matchesFilter(order,filter);
|
||
function renderBoard(){
|
||
const filters=[['all','Todos'],['textil','Têxtil'],['uv','UV'],['entrega','Entrega'],['retirada','Retirada'],
|
||
['parados','Parados'],['manual','Preparar à mão'],['cancelados','Cancelados']];
|
||
// Each chip says how many orders in progress it would show.
|
||
const inProgress=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at);
|
||
$('filters').replaceChildren(...filters.map(([key,label])=>{
|
||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(filter===key));
|
||
b.append(node('span',String((key==='cancelados'?board.orders:inProgress).filter(o=>matchesFilter(o,key)).length),'chip-n'));
|
||
if(key==='parados')b.title='Sem mudar de etapa há mais de '+LATE_HOURS+' h';
|
||
b.onclick=()=>{filter=key;renderBoard();};return b;}));
|
||
const active=board.orders.filter(o=>['rec','tra','fil','imp'].includes(o.state));
|
||
const queued=active.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
||
$('board-summary').textContent=metres(queued)+' em produção';
|
||
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
||
const column=node('section',undefined,'col');column.dataset.state=state;column.style.setProperty('--c',STAGE_COLORS[state]);
|
||
// A queue: the order paid first is on top, the newest at the bottom, however
|
||
// the list was put together (older finished ones, one opened from the search).
|
||
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>queueKey(a)-queueKey(b)||a.number-b.number);
|
||
const total=orders.reduce((s,o)=>s+o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0),0);
|
||
const head=node('div',undefined,'col-head');const line=node('div');
|
||
const swatch=node('span',undefined,'swatch');swatch.style.setProperty('--c',STAGE_COLORS[state]);
|
||
// Finished orders are a recent window, not the whole history: say so.
|
||
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
||
line.append(swatch,node('h2',title),node('span',count,'n'));
|
||
head.append(line,node('small',orders.length?metres(total)+' no total':'vazio'));
|
||
column.append(head);
|
||
for(const order of orders)column.append(card(order));
|
||
if(state==='fin'&&finishedMore&&filter==='all')moreButton(column,true,loadOlderFinished);
|
||
// Dragging only goes forward to the next stage. Going back or asking for a
|
||
// correction needs a reason, so those happen in the order panel.
|
||
column.ondragover=e=>{
|
||
if(dragging?.state===state&&state!=='fin'){e.preventDefault();markDrop(column,e.clientY);return;}
|
||
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');};
|
||
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
|
||
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
|
||
const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain'));
|
||
if(!order)return;
|
||
try{
|
||
if(order.state!==state)await move(order,state);
|
||
else if(state!=='fin')await reorder(order,column,e.clientY);
|
||
}catch(error){say(error.message,true);}
|
||
finally{clearDrop();}};
|
||
return column;
|
||
}));
|
||
}
|
||
// An operator's test order: no payment, no Tiny, no WhatsApp.
|
||
const isTest=order=>order.payment?.provider==='teste';
|
||
function card(order){
|
||
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at;
|
||
if(order.id===openOrder)c.classList.add('open');
|
||
const s=order.snapshot;
|
||
const top=node('div',undefined,'row');
|
||
top.append(node('span','#'+order.number,'num'),...(isTest(order)?[node('span','TESTE','tag-teste')]:[]),node('span',ago(order.updated_at),'age'));
|
||
const meta=node('div',undefined,'meta');
|
||
meta.append(gradePill(lowestGrade(s.items)),productBadge(s.items),
|
||
node('b',metres(s.items.reduce((t,i)=>t+Number(i.billed_metres),0)),'mtr'));
|
||
// What needs attention, as badges; a finished order needs none.
|
||
const flags=node('div',undefined,'flags');
|
||
if(order.cancelled_at)flags.append(badge('Cancelado','bad','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason));
|
||
else if(order.state!=='fin'){
|
||
const p=printState(order);
|
||
flags.append(badge((p.tone==='ok'?'✓ ':p.tone==='warn'?'! ':'')+p.text,p.tone));
|
||
if(s.items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva','warn','O cliente aceitou a ressalva de resolução'));
|
||
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
|
||
}
|
||
c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination));
|
||
if(flags.children.length)c.append(flags);
|
||
c.onclick=()=>openPanel(order.id);
|
||
c.ondragstart=e=>{
|
||
dragging=order;
|
||
e.dataTransfer.setData('text/plain',order.id);
|
||
const forward=board.transitions[order.state].filter(s=>s!=='cor');
|
||
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
|
||
say((forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou ')+', ou ':'')+'arraste para cima ou para baixo para mudar a prioridade',false,60000);
|
||
};
|
||
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
|
||
return c;
|
||
}
|
||
// The column's queue: payment time, unless an operator dragged the card to
|
||
// another place (queue_key, seconds like the payment time).
|
||
const queueKey=o=>o.queue_key!=null?Number(o.queue_key):new Date(o.created_at).getTime()/1000;
|
||
let dragging=null;
|
||
// Where a card dropped at this height lands: the card it goes before, if any.
|
||
function dropTarget(column,y){
|
||
const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id);
|
||
return cards.find(c=>{const r=c.getBoundingClientRect();return y<r.top+r.height/2;})||null;
|
||
}
|
||
function markDrop(column,y){
|
||
clearDrop();
|
||
const target=dropTarget(column,y);
|
||
if(target)target.classList.add('drop-before');
|
||
else{const cards=[...column.querySelectorAll('.card')].filter(c=>c.dataset.card!==dragging?.id);cards.at(-1)?.classList.add('drop-after');}
|
||
}
|
||
function clearDrop(){for(const c of document.querySelectorAll('.drop-before,.drop-after'))c.classList.remove('drop-before','drop-after');}
|
||
async function reorder(order,column,y){
|
||
const target=dropTarget(column,y);
|
||
const cards=[...column.querySelectorAll('.card')].map(c=>c.dataset.card).filter(id=>id!==order.id);
|
||
const at=target?cards.indexOf(target.dataset.card):cards.length;
|
||
const after=cards[at-1]||null, before=cards[at]||null;
|
||
if(!after&&!before)return;
|
||
// Dropped where it already was: nothing to save.
|
||
const current=[...column.querySelectorAll('.card')].map(c=>c.dataset.card);
|
||
const was=current.indexOf(order.id);
|
||
if(current[was-1]===(after||undefined)&¤t[was+1]===(before||undefined))return;
|
||
await api('/orders/'+order.id+'/queue',{after,before});
|
||
await load();
|
||
}
|
||
async function loadOlderFinished(){
|
||
const shown=board.orders.filter(o=>o.state==='fin').sort((a,b)=>a.created_at<b.created_at?-1:1);
|
||
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
|
||
if(oldest){params.set('before_created_at',oldest.created_at);params.set('before_id',oldest.id);}
|
||
const page=absorb(await api('/orders/finished?'+params));
|
||
const known=new Set(board.orders.map(o=>o.id));
|
||
const fresh=page.orders.filter(o=>!known.has(o.id));
|
||
olderFinished.push(...fresh);board.orders.push(...fresh);finishedMore=page.has_more;renderBoard();
|
||
}
|
||
async function move(order,state,reason=''){
|
||
await api('/orders/'+order.id+'/move',{state,version:order.version,reason});
|
||
await load();
|
||
}
|
||
|
||
// ---- Order panel ---------------------------------------------------------
|
||
|
||
function openPanel(id){openOrder=id;const order=board.orders.find(o=>o.id===id);$('drawer').hidden=false;renderPanel(order);renderBoard();}
|
||
function closePanel(){openOrder=null;$('drawer').hidden=true;$('panel').replaceChildren();if(board)renderBoard();}
|
||
$('scrim').onclick=closePanel;
|
||
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&openOrder)closePanel();});
|
||
|
||
function layoutPreview(production){
|
||
const ns='http://www.w3.org/2000/svg', w=Number(production.film_width_cm), h=Math.max(1,Number(production.height_cm));
|
||
const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
|
||
svg.setAttribute('aria-label','Montagem: '+production.placements.length+' peças em '+w+' × '+h+' cm');
|
||
const film=document.createElementNS(ns,'rect');film.setAttribute('width',w);film.setAttribute('height',h);film.setAttribute('fill','#0F1113');svg.append(film);
|
||
const colors=['#2BB6D9','#E0508F','#E9C23A','#6FD19C','#FF8B2B','#A78BFA'];
|
||
for(const p of production.placements){const r=document.createElementNS(ns,'rect');
|
||
r.setAttribute('x',p.x_cm);r.setAttribute('y',p.y_cm);r.setAttribute('width',p.width_cm);r.setAttribute('height',p.length_cm);
|
||
r.setAttribute('fill',colors[p.source_index%colors.length]);r.setAttribute('fill-opacity','.55');svg.append(r);}
|
||
return svg;
|
||
}
|
||
function renderPanel(order){
|
||
const token=++openToken, panel=$('panel');panel.dataset.order=order.id;
|
||
const color=STAGE_COLORS[order.state];
|
||
const head=node('div',undefined,'panel-head');
|
||
const row=node('div',undefined,'row');
|
||
const stage=node('span',board.states[order.state],'stage');stage.style.setProperty('--c',color);
|
||
const close=node('button',undefined,'close');close.type='button';close.setAttribute('aria-label','Fechar');close.append(icon(['M6 6l12 12M18 6L6 18']));close.onclick=closePanel;
|
||
const test=isTest(order)?node('span','TESTE','tag-teste'):null;
|
||
if(test)test.title='Pedido de teste: sem pagamento, não vai ao Tiny nem ao WhatsApp';
|
||
const code=node('span',undefined,'ocode');code.append('Pedido '+orderCode(order.id),copyButton(orderCode(order.id),'Copiar código do pedido'));
|
||
code.title='O código que o cliente vê';
|
||
row.append(node('span','#'+order.number,'num'),stage,...(test?[test]:[]),code,close);
|
||
// What was paid and when, and whether it is stuck: the first things asked of an order.
|
||
const paid=node('div',undefined,'paidline');
|
||
paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at));
|
||
if(order.cancelled_at)paid.append(badge('Cancelado','bad'));
|
||
else if(stalled(order))paid.append(badge('⏱ Parado há '+hoursSince(order.updated_at)+' h','bad'));
|
||
const steps=node('ol',undefined,'steps');steps.setAttribute('aria-label','Etapas');
|
||
const at=FLOW.indexOf(order.state);
|
||
for(const [i,s] of FLOW.entries()){const li=node('li',board.states[s]);li.style.setProperty('--c',STAGE_COLORS[s]);
|
||
if(at>=0&&i<at)li.classList.add('done');if(i===at)li.classList.add('now');steps.append(li);}
|
||
head.append(row,paid,steps,moves(order));
|
||
|
||
const body=node('div',undefined,'panel-body');
|
||
const s=order.snapshot, dest=s.destination;
|
||
const facts=node('section',undefined,'facts');
|
||
const who=node('div',undefined,'fcard');
|
||
const doc=node('span',undefined,'line');doc.append('CNPJ '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar CNPJ'));
|
||
who.append(node('p','Cliente','eyebrow'),buyerBlock(s),doc);
|
||
const zap=whatsappLink(s.customer.zap);
|
||
if(zap){const a=node('a','Abrir conversa','zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(icon(ICON_CHAT));who.append(a);}
|
||
const where=node('div',undefined,'fcard');
|
||
const placeLine=node('b');placeLine.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?dest.recipient:'Retirada em Franca');
|
||
where.append(node('p','Entrega','eyebrow'),placeLine,
|
||
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica'));
|
||
if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
|
||
facts.append(who,where);
|
||
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
|
||
const itemsList=node('div');itemsList.style.display='flex';itemsList.style.flexDirection='column';itemsList.style.gap='10px';
|
||
s.items.forEach((item,index)=>itemsList.append(itemCard(order,item,index)));
|
||
items.append(itemsList);
|
||
const finals=node('section',undefined,'finals');finals.append(node('p','Arquivos finais','eyebrow'),node('p','Carregando…','faint'));
|
||
const history=node('section');history.append(node('p','Histórico','eyebrow'),node('p','Carregando…','faint'));
|
||
body.append(facts,items,finals,history);
|
||
panel.replaceChildren(head,body);
|
||
|
||
api('/orders/'+order.id+'/files').then(rows=>{if(token===openToken)finalsSection(order,rows,finals);}).catch(e=>say(e.message,true));
|
||
api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken)historySection(order,rows,history);}).catch(e=>say(e.message,true));
|
||
}
|
||
function moves(order){
|
||
const box=node('div',undefined,'panel-actions');
|
||
if(order.cancelled_at){
|
||
const note=node('div',undefined,'callout bad');
|
||
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
|
||
const remove=button('Excluir pedido',async()=>{
|
||
if(!window.confirm('Excluir o pedido #'+order.number+' de vez? Ele some do Kanban com o histórico. O pagamento continua registrado no Mercado Pago.'))return;
|
||
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido #'+order.number+' excluído.');await load();
|
||
},'btn danger');remove.style.alignSelf='flex-start';
|
||
box.append(note,remove);return box;
|
||
}
|
||
const row=node('div',undefined,'moves');
|
||
// One form open at a time under the buttons.
|
||
const forms=[];
|
||
let sync=()=>{};
|
||
const toggle=form=>{const show=form.hidden;for(const f of forms)f.hidden=true;form.hidden=!show;sync();
|
||
if(show)form.querySelector('textarea,input:not([type=checkbox]):not([hidden])')?.focus();};
|
||
const reason=node('form',undefined,'reason');reason.hidden=true;forms.push(reason);
|
||
let step=null;
|
||
for(const next of board.transitions[order.state]){
|
||
if(next==='cor'){
|
||
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
||
b.onclick=()=>toggle(reason);row.append(b);
|
||
}else if(next==='fil'&&!finalDone(order)){
|
||
// The queue needs an approved final: approving it is the next step,
|
||
// shown first, with the file that would be printed.
|
||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||
const upload=finalForm(order,all?ready.map(()=>null):ready);forms.unshift(upload);
|
||
const text=node('div');text.append(node('b','Próximo passo: aprovar o arquivo final'));
|
||
if(all){
|
||
text.append(node('span','Baixe e confira. É este arquivo que vai para a impressão.'));
|
||
const files=node('div',undefined,'readyfiles');
|
||
ready.forEach((r,i)=>{const line=node('div',undefined,'readyfile');
|
||
line.append(node('span',(many?'Item '+(i+1)+' · ':'')+FINAL_TITLE[r.source],'faint'),node('b',r.name),
|
||
downloadButton('Baixar',download(r.upload_id),'btn ghost small'));files.append(line);});
|
||
text.append(files);
|
||
}else text.append(node('span',ready.some(Boolean)?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.'
|
||
:'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.'));
|
||
const actions=node('div',undefined,'stepactions');
|
||
const b=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>toggle(upload),'btn primary');
|
||
b.dataset.approve='';actions.append(b);
|
||
if(all){const other=node('button','Enviar outro arquivo','btn ghost');other.type='button';other.onclick=()=>toggle(upload);actions.append(other);}
|
||
// The upload form opens inside the step, in place of its buttons.
|
||
const cancel=node('button','Cancelar','linkbtn');cancel.type='button';cancel.onclick=()=>toggle(upload);
|
||
upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden;};
|
||
text.append(actions,upload);
|
||
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
|
||
}else{
|
||
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
||
}
|
||
}
|
||
if(!row.children.length)row.append(node('span','Pedido concluído.','muted'));
|
||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||
const previous=board.back?.[order.state];
|
||
const sub=node('div',undefined,'subactions');
|
||
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
|
||
if(previous){
|
||
const b=node('button','← Voltar para '+board.states[previous],'linkbtn');b.type='button';b.dataset.back=previous;
|
||
b.onclick=()=>toggle(backForm);sub.append(b);
|
||
const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000;
|
||
const go=node('button','Voltar para '+board.states[previous],'btn');
|
||
backForm.append(why,go);
|
||
backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}};
|
||
}
|
||
// Rare and destructive: behind a menu. A test order is deleted; a paid one
|
||
// is cancelled, with a reason, and kept.
|
||
const cancelForm=node('form',undefined,'reason');cancelForm.hidden=true;forms.push(cancelForm);
|
||
const menu=node('div',undefined,'menu');menu.hidden=true;menu.setAttribute('role','menu');
|
||
if(isTest(order)){
|
||
menu.append(button('Excluir pedido de teste',async()=>{
|
||
menu.hidden=true;
|
||
if(!window.confirm('Excluir o pedido de teste #'+order.number+'? Ele some do Kanban, com o histórico.'))return;
|
||
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();
|
||
},'menuitem bad'));
|
||
}else{
|
||
const b=node('button','Cancelar pedido','menuitem bad');b.type='button';
|
||
b.onclick=()=>{menu.hidden=true;toggle(cancelForm);};menu.append(b);
|
||
const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000;
|
||
const go=node('button','Cancelar pedido #'+order.number,'btn danger');
|
||
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago, e o pedido no Tiny se cancela lá.','muted'),why,go);
|
||
cancelForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;
|
||
try{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}
|
||
catch(error){say(error.message,true);go.disabled=false;}};
|
||
}
|
||
const more=node('button','⋯','btn ghost more');more.type='button';more.title='Mais ações';more.setAttribute('aria-label','Mais ações');
|
||
more.setAttribute('aria-haspopup','menu');
|
||
more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden;
|
||
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});};
|
||
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);row.append(wrap);
|
||
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
|
||
const sendFix=node('button','Enviar para correção','btn danger');
|
||
reason.append(text,sendFix);
|
||
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
||
box.append(...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||
}
|
||
// ---- Final files: the file each item is printed from, approved by an operator.
|
||
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
|
||
const FINAL_SOURCE={correction:'correção do cliente',generated:'PDF gerado',original:'original'};
|
||
const FINAL_TITLE={correction:'Correção do cliente',generated:'PDF gerado',original:'Original do cliente'};
|
||
// Per item, a file that can be approved as it is, or null: the customer's
|
||
// correction, or else the generated PDF (or the original that already is one).
|
||
// After a correction, a generated file reproduces artwork nobody wants printed.
|
||
function readyFinals(order){
|
||
const fixes=order.corrections||[];
|
||
return order.snapshot.items.map((item,index)=>{
|
||
const fix=fixes.find(f=>f.item_index===index);
|
||
if(fix)return fix.expired?null:{upload_id:fix.upload_id,name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'};
|
||
const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
|
||
if(!made)return null;
|
||
const original=made.detail?.source==='original';
|
||
return {upload_id:made.upload_id,name:made.name,source:original?'original':'generated',label:(original?'O original (':'PDF gerado (')+made.name+')'};
|
||
});
|
||
}
|
||
async function approveReady(order,ready){
|
||
const many=ready.length>1;
|
||
if(!window.confirm('Conferiu o arquivo? Ele vai ser o arquivo de impressão.\n\n'+
|
||
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))return;
|
||
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
|
||
await load();say('Arquivo final aprovado. Agora é só mover para a fila.');
|
||
}
|
||
// The form for a file the operator prepared, or to pick per item; ready
|
||
// files come ticked.
|
||
function finalForm(order,ready){
|
||
const form=node('form',undefined,'finalform');form.hidden=true;
|
||
const inputs=order.snapshot.items.map((item,index)=>{
|
||
const slot=node('label',undefined,'slot');slot.append('Item '+(index+1)+' · '+PRODUCT[item.mode]);
|
||
const input=node('input');input.type='file';input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
||
const file=ready[index];
|
||
if(file){
|
||
const use=node('input');use.type='checkbox';use.checked=true;use.dataset.useGenerated=index;input.required=false;input.hidden=true;
|
||
use.onchange=()=>{input.hidden=use.checked;input.required=!use.checked;};
|
||
const choice=node('label',undefined,'check');choice.append(use,'Usar: '+file.label);
|
||
slot.append(choice);input.generated=()=>use.checked?file.upload_id:null;
|
||
}
|
||
slot.append(input);form.append(slot);return input;
|
||
});
|
||
const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;
|
||
const check=node('input');check.type='checkbox';check.required=true;check.dataset.confirm='';
|
||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos conferidos');
|
||
const submit=node('button','Aprovar arquivo final','btn primary');
|
||
form.append(note,checked,submit);
|
||
form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;try{
|
||
const refs=[];
|
||
for(const [index,input] of inputs.entries()){
|
||
const generated=input.generated?.();
|
||
if(generated){refs.push({item_index:index,upload_id:generated});continue;}
|
||
for(const file of input.files){
|
||
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
|
||
refs.push({item_index:index,upload_id:uid});
|
||
}
|
||
}
|
||
await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:note.value});
|
||
await load();say('Arquivo final aprovado.');
|
||
}catch(error){say(error.message,true);submit.disabled=false;}};
|
||
return form;
|
||
}
|
||
const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'PDF gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'};
|
||
function itemCard(order,item,index){
|
||
const row=(order.print_files||[]).find(r=>r.item_index===index);
|
||
const box=node('div',undefined,'item');
|
||
if(row&&(row.status==='manual'||row.status==='failed')&&!(order.corrections||[]).some(f=>f.item_index===index))box.classList.add('attention');
|
||
const preview=itemPreview(item);
|
||
const body=node('div',undefined,'body');
|
||
const spec=item.production;
|
||
const title=node('div',undefined,'title');title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),node('span',metres(item.billed_metres),'mono'));
|
||
body.append(title,facts([['Folha',sheetSize(spec)],['Peças',spec?String(spec.placements.length):null],
|
||
['Metro',item.unit_cents?money(item.unit_cents):null],['Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null]]));
|
||
if(item.quality_status==='warning')body.append(badge('! Ressalva de resolução aceita','warn'));
|
||
// After a customer correction, that file is the artwork: the generated
|
||
// print file, or the reason it could not be made, no longer applies.
|
||
const fix=(order.corrections||[]).find(f=>f.item_index===index);
|
||
if(fix){
|
||
const file=node('div',undefined,'file');
|
||
file.append(icon(ICON_OK),node('span','Correção do cliente recebida · '+fix.name,'ok'));body.append(file);
|
||
}
|
||
// The print file: a line when it is fine, a callout when someone must act.
|
||
else if(!row)body.append(node('div','Arquivo de impressão ainda não gerado','line'));
|
||
else if(row.status==='manual'||row.status==='failed'){
|
||
const call=node('div',undefined,'callout');
|
||
call.append(node('b',row.status==='failed'?'! Falhou ao gerar':'! Preparar à mão'),
|
||
node('span',row.detail?.reason||'Monte a folha a partir do original.'));
|
||
body.append(call);
|
||
}else{
|
||
const original=row.status==='ready'&&row.detail?.source==='original';
|
||
const tone=row.status==='ready'?'ok':'muted';
|
||
const file=node('div',undefined,'file');
|
||
file.append(tone==='ok'?icon(ICON_OK):'',node('span',(original?'O original é o arquivo de impressão':PRINT_TEXT[row.status])+
|
||
(row.status==='ready'&&row.name&&!original?' · '+row.name:''),tone));
|
||
body.append(file);
|
||
if(row.status==='ready'&&row.detail&&!original){
|
||
const extra=[row.detail.min_dpi?'menor resolução '+row.detail.min_dpi+' DPI':'',row.detail.vector_sources?'PDF vetorial':''].filter(Boolean).join(' · ');
|
||
if(extra)body.append(node('div',extra,'line'));
|
||
}
|
||
}
|
||
if(['rec','tra','cor'].includes(order.state)){
|
||
const done=(order.final_items||[]).includes(index), status=node('div',undefined,'file');
|
||
status.append(icon(done?ICON_OK:ICON_WARN),node('span',done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn'));
|
||
body.append(status);
|
||
}
|
||
const buttons=node('div',undefined,'buttons');
|
||
if(fix&&!fix.expired)buttons.append(downloadButton('Correção',download(fix.upload_id)));
|
||
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
|
||
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
|
||
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
|
||
if(!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
|
||
buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost'));
|
||
body.append(buttons);
|
||
box.append(preview,body);return box;
|
||
}
|
||
function finalsSection(order,revisions,section){
|
||
section.replaceChildren(node('p','Arquivos finais','eyebrow'));
|
||
for(const file of revisions){
|
||
const rev=node('div',undefined,'rev');
|
||
rev.append(node('b',(file.kind==='final'?'Final':'Correção do cliente')+' · item '+(file.item_index+1)+' · '+file.name),
|
||
node('span',(file.expired?'expirado':file.active?'atual':'substituído')+' · '+when(file.created_at)+' · '+file.note,'faint'));
|
||
if(!file.expired){const b=downloadButton('Baixar',download(file.upload_id),'btn ghost');b.style.alignSelf='flex-start';rev.append(b);}
|
||
section.append(rev);
|
||
}
|
||
if(!revisions.length)section.append(node('p','Nenhum arquivo final ainda.','faint'));
|
||
// Approving is the button at the top; this is for replacing an approved
|
||
// final, or sending one before the art is marked as handled.
|
||
// Before approval in Arte tratada, the step at the top is the way in.
|
||
if(!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
|
||
const form=finalForm(order,readyFinals(order).map(()=>null));
|
||
const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button';
|
||
open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();};
|
||
section.append(open,form);
|
||
}
|
||
function historySection(order,rows,section){
|
||
const list=node('ol',undefined,'timeline');
|
||
const entry=(color,title,who,at,reason)=>{
|
||
const li=node('li');li.style.setProperty('--c',color);
|
||
const text=node('div');text.append(node('b',title),node('span',' · '+who,'faint'));
|
||
if(reason)text.append(node('span',' · '+reason,'muted'));
|
||
li.append(text,node('small',when(at)));return li;
|
||
};
|
||
for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+board.states[r.to_state]:board.states[r.to_state],r.operator,r.created_at,r.reason));
|
||
list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':'Site',order.created_at,''));
|
||
section.replaceChildren(node('p','Histórico','eyebrow'),list);
|
||
}
|
||
|
||
// ---- 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)/96));}
|
||
function fitQuotes(){
|
||
const list=$('quote-list'), rows=[...list.querySelectorAll('.qitem')];
|
||
if($('tab-quotes').hidden||!rows.length||quoteFitting>3)return;
|
||
const room=list.clientHeight, gap=8;
|
||
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&"eTotal){quotePage=Math.ceil(quoteTotal/quoteSize);return loadQuotes();}
|
||
renderQuotes();
|
||
}
|
||
function renderQuotes(){
|
||
const kinds=[['pending','A revisar',board.pending_total],['approved','Aprovadas, aguardando pagamento',board.approved_total]];
|
||
$('quote-filters').replaceChildren(...kinds.map(([key,label,count])=>{
|
||
const b=node('button',label+' · '+count,'chip');b.type='button';b.setAttribute('aria-pressed',String(quoteKind===key));
|
||
b.onclick=()=>{quoteKind=key;quotePage=1;quoteFitting=0;currentQuote=null;loadQuotes().catch(e=>say(e.message,true));};return b;}));
|
||
// Product, layout and warning: each chip toggles; the two of a pair exclude each other.
|
||
const toggles=[['product','textil','Têxtil'],['product','uv','UV'],['layout','folha','Folha montada'],
|
||
['layout','avulsa','Artes avulsas'],['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,'chip');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;}));
|
||
if(!currentQuote||(!quoteRows.some(q=>q.id===currentQuote.id)&¤tQuote.status==='pending_review'))currentQuote=quoteRows[0]||null;
|
||
else currentQuote=quoteRows.find(q=>q.id===currentQuote.id)||currentQuote;
|
||
const list=quoteRows.map(q=>{
|
||
const b=node('button',undefined,'qitem');b.type='button';b.dataset.quotePick=q.id;b.setAttribute('aria-current',String(q.id===currentQuote?.id));
|
||
const items=q.draft.items;
|
||
const head=node('div',undefined,'qhead');
|
||
// 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';head.append(dot);}
|
||
head.append(buyerBlock(q.draft,'qmail'),node('b',q.approved?money(q.approved.total_cents):'a revisar','qtotal'+(q.approved?'':' muted')));
|
||
const meta=node('div',undefined,'meta');
|
||
meta.append(gradePill(lowestGrade(items)),productBadge(items),node('b',metres(quoteMetres(q)),'mtr'),
|
||
place(q.draft.destination),node('span',ago(q.created_at),'age'));
|
||
const flags=node('div',undefined,'flags');
|
||
if(items.some(i=>i.production?.version!==2))flags.append(badge('Montagem antiga','bad','Peça uma nova cotação ao cliente'));
|
||
else if(items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva aceita','warn','O cliente aceitou a ressalva de resolução'));
|
||
if(!q.approved&&q.review_reason)flags.append(badge('! '+q.review_reason,'warn','Revisão manual: '+q.review_reason));
|
||
// Approved by the Site is the rule; only a person's review is worth a line.
|
||
if(q.approved&&!q.auto_approved)flags.append(badge('Revisada pela equipe',''));
|
||
const pay=paymentBadge(q.payment);if(pay)flags.append(pay);
|
||
const main=node('div',undefined,'qmain');main.append(head,meta);if(flags.children.length)main.append(flags);
|
||
b.append(artBox(items,'qart'),main);b.onclick=()=>{currentQuote=q;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.','faint'));
|
||
$('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);
|
||
$('reviews').replaceChildren(currentQuote?review(currentQuote):node('p','Selecione uma cotação.','note'));
|
||
}
|
||
function review(quote){
|
||
const card=node('article',undefined,'review');card.style.display='contents';card.dataset.quote=quote.id;
|
||
const head=node('div',undefined,'head');const title=node('div',undefined,'qtitle');
|
||
const status={pending_review:['● A revisar','accent'],approved:['● Aprovada · aguardando pagamento','ok'],
|
||
expired:['Expirada','bad'],paid:['● Paga','info']}[quote.status]||[quote.status,''];
|
||
const name=node('div',undefined,'qname');name.append(buyerBlock(quote.draft),badge(...status));
|
||
const pay=paymentBadge(quote.payment);if(pay)name.append(pay);
|
||
const sub=node('div',undefined,'qsub');const c=quote.draft.customer;
|
||
const doc=node('span');doc.append('CNPJ '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar CNPJ'));sub.append(doc);
|
||
const zap=whatsappLink(c.zap);
|
||
if(zap){const a=node('a',c.zap,'zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));sub.append(a);}
|
||
sub.append(place(quote.draft.destination,'Entrega em '),node('span','#'+quote.id.slice(0,8)+' · '+ago(quote.created_at),'faint'));
|
||
title.append(name,sub);head.append(title);
|
||
if(quote.approved){const total=node('div',undefined,'qbig');total.append(node('span','Total'),node('b',money(quote.approved.total_cents)));head.append(total);}
|
||
const content=node('div',undefined,'content');
|
||
const foot=node('div',undefined,'foot');
|
||
if(quote.status==='pending_review'&"e.draft.items.some(item=>item.production?.version!==2)){
|
||
content.append(node('p','Montagem antiga. Solicite uma nova cotação ao cliente.','muted'));
|
||
card.append(head,content);return card;
|
||
}
|
||
if(quote.status!=='pending_review'){
|
||
if(quote.status==='expired')content.append(node('p','Cotação expirada. O cliente precisa solicitar outra.','muted'));
|
||
quote.draft.items.forEach((item,index)=>content.append(quoteItem(item,null,quote.approved?.items?.[index])));
|
||
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'));
|
||
content.append(sums);
|
||
}
|
||
card.append(head,content);
|
||
if(quote.status==='approved'){
|
||
foot.append(discardButton(quote));
|
||
// Tries the whole production flow without a payment.
|
||
foot.append(button('Criar pedido de teste',async()=>{
|
||
if(!window.confirm('Criar um pedido de TESTE para esta cotação? Não cobra nada e não vai para o Tiny nem para o WhatsApp.'))return;
|
||
const order=await api('/quotes/'+quote.id+'/test-order',{});
|
||
say('Pedido de teste #'+order.number+' criado em Arte recebida.');await load();
|
||
},'btn ghost'));
|
||
card.append(foot);
|
||
}
|
||
return card;
|
||
}
|
||
const form=node('form');form.style.display='contents';
|
||
const edits=quote.draft.items.map(item=>{const fields={};content.append(quoteItem(item,fields));
|
||
return ()=>({...item,metres:fields.metres.value,grade:Number(fields.grade.value)});});
|
||
foot.append(discardButton(quote));
|
||
const check=node('input');check.type='checkbox';check.required=true;
|
||
// Not "confirm": that name in this function hid window.confirm from the
|
||
// test-order button above, which then failed before asking anything.
|
||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos, metragem e nota conferidos');
|
||
const submit=node('button','Aprovar cotação','btn primary');
|
||
foot.append(checked,submit);
|
||
form.append(content,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;}};
|
||
card.append(head,form);return card;
|
||
}
|
||
// An unpaid quote leaves the list and can no longer be paid.
|
||
function discardButton(quote){
|
||
return button('Descartar cotação',async()=>{
|
||
if(!window.confirm('Descartar esta cotação? Ela sai do Kanban e o cliente não consegue mais pagá-la.'))return;
|
||
await api('/quotes/'+quote.id+'/discard',{});currentQuote=null;say('Cotação descartada.');await load();
|
||
},'btn ghost discard');
|
||
}
|
||
function quoteItem(item,fields,priced){
|
||
const box=node('div',undefined,'item');
|
||
const preview=itemPreview(item);
|
||
if(!preview.classList.contains('with-art'))preview.style.width='160px';
|
||
const body=node('div',undefined,'body');
|
||
const spec=item.production;
|
||
const title=node('div',undefined,'title');
|
||
title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),...(priced?[node('span',money(priced.total_cents),'mono')]:[]));
|
||
body.append(title,facts([['Folha',sheetSize(spec)],['Cobrado',priced?metres(priced.billed_metres):null],
|
||
['Metro',priced?money(priced.unit_cents):null],['Peças',spec?String(spec.placements.length):null],
|
||
['Arquivos',spec?String(spec.sources.length):null]]));
|
||
const chips=node('div',undefined,'flags');
|
||
chips.append(item.quality_status==='ok'?badge('✓ Qualidade conferida','ok'):item.quality_status==='warning'?
|
||
badge(item.quality_acknowledged?'! Ressalva aceita pelo cliente':'! Ressalva não aceita','warn'):badge('Qualidade não conferida',''));
|
||
body.append(chips);
|
||
if(fields){
|
||
const grid=node('div',undefined,'fields');
|
||
const asked=node('label','Metros do cliente');const a=node('input');a.value=item.metres;a.readOnly=true;asked.append(a);
|
||
const m=node('label','Metros conferidos');fields.metres=node('input');Object.assign(fields.metres,{type:'number',min:'0.001',max:'12000',step:'any',value:item.metres,required:true});m.append(fields.metres);
|
||
const g=node('label','Nota conferida');fields.grade=node('input');Object.assign(fields.grade,{type:'number',min:'0',max:'100',step:'1',value:item.grade,required:true});g.append(fields.grade);
|
||
grid.append(asked,m,g);body.append(grid);
|
||
}
|
||
const buttons=node('div',undefined,'buttons');
|
||
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
|
||
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
|
||
body.append(buttons);box.append(preview,body);return box;
|
||
}
|
||
|
||
// ---- Payments and integrations ------------------------------------------
|
||
|
||
const tinyResult=new URLSearchParams(location.search).get('tiny');
|
||
const tinyNotice=tinyResult?(tinyResult==='connected'?' · Tiny conectado.':' · Não foi possível conectar o Tiny. Tente de novo.'):'';
|
||
if(tinyResult)history.replaceState(null,'',location.pathname);
|
||
function tinyHeader(){
|
||
const t=board.tiny||{};const el=$('tiny');
|
||
if(!t.configured){el.textContent='';return;}
|
||
const trouble=!t.connected||t.problem;
|
||
el.textContent=!t.connected?'Tiny não conectado':t.problem?'Tiny: verificar conexão':'Tiny conectado';
|
||
el.style.setProperty('--dot',trouble?'var(--warn)':'var(--fin)');
|
||
}
|
||
const TINY_PROBLEMS={refused:'O Tiny recusou a renovação da conexão. Conecte de novo.',
|
||
expired:'A conexão com o Tiny expirou. Conecte de novo.',
|
||
'renewal-failing':'A última renovação falhou; o sistema tenta de novo sozinho.',
|
||
expiring:'A conexão expira em breve e não está sendo renovada.'};
|
||
function tinyDetail(t){
|
||
if(!t.connected_by)return 'Conecte com uma conta do Tiny.';
|
||
const parts=[t.connected_by+' · conectado em '+when(t.connected_at),'renovado em '+when(t.renewed_at),
|
||
t.offline?'sem expiração diária':t.expires_at?'válido até '+when(t.expires_at):'',
|
||
'envio de pedidos '+(t.orders_enabled?'ativo':'desativado')].filter(Boolean);
|
||
const problem=TINY_PROBLEMS[t.problem];
|
||
return (problem?problem+(t.failed_at&&t.problem!=='expired'?' (falha em '+when(t.failed_at)+')':'')+' · ':'')+parts.join(' · ');
|
||
}
|
||
function integration(name,state,tone,text,actions=[]){
|
||
const box=node('div',undefined,'integration');
|
||
const head=node('div',undefined,'head');const dot=node('span',undefined,'dot');
|
||
const colors={ok:['var(--fin)','var(--ok)'],warn:['var(--warn)','var(--warn)'],off:['#5B6168','var(--muted)']}[tone];
|
||
dot.style.setProperty('--dot',colors[0]);const em=node('em',state);em.style.setProperty('--dotx',colors[1]);
|
||
head.append(dot,node('b',name),em);box.append(head,node('p',text));
|
||
if(actions.length){const b=node('div',undefined,'buttons');b.append(...actions);box.append(b);}
|
||
return box;
|
||
}
|
||
// The page bar under every list: page size, range, first/previous/page/next/last.
|
||
const PAGE_SIZES=[10,20,50,100];
|
||
function pager({page,size,total,noun,onPage,onSize,compact=false,fixedSize=false}){
|
||
const pages=Math.max(1,Math.ceil(total/size));
|
||
const bar=node('div',undefined,'pager'+(compact?' compact':''));
|
||
const sizeLabel=node('label',undefined,'pager-size');
|
||
const select=node('select');select.setAttribute('aria-label','Itens por página');
|
||
for(const n of PAGE_SIZES){const o=node('option',String(n));o.value=String(n);o.selected=n===size;select.append(o);}
|
||
select.onchange=()=>onSize(Number(select.value));
|
||
sizeLabel.append('Mostrar',select,'por página');
|
||
const nav=node('div',undefined,'pager-nav');
|
||
const from=total?(page-1)*size+1:0, to=Math.min(total,page*size);
|
||
const go=(label,aria,target,disabled)=>{const b=node('button',label,'pg');b.type='button';b.setAttribute('aria-label',aria);b.disabled=disabled;b.onclick=()=>onPage(target);return b;};
|
||
const pageLabel=node('label',undefined,'pager-page');
|
||
const input=node('input');input.type='number';input.min='1';input.max=String(pages);input.value=String(page);input.setAttribute('aria-label','Página');
|
||
input.onchange=()=>onPage(Math.min(pages,Math.max(1,Math.round(Number(input.value))||1)));
|
||
pageLabel.append(compact?'':'Página',input,'de '+pages);
|
||
nav.append(go('«','Primeira página',1,page<=1),go('‹','Página anterior',page-1,page<=1),pageLabel,
|
||
go('›','Próxima página',page+1,page>=pages),go('»','Última página',pages,page>=pages));
|
||
bar.append(...(fixedSize?[]:[sizeLabel]),node('span',(compact?'':'Mostrando ')+from+' a '+to+' de '+total+(compact?'':' '+noun),'pager-range'),nav);
|
||
return bar;
|
||
}
|
||
function chips(container,options,current,pick){
|
||
container.replaceChildren(...options.map(([key,label])=>{
|
||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(current===key));
|
||
b.onclick=()=>pick(key);return b;}));
|
||
}
|
||
function moreButton(container,has,fn){
|
||
if(!has)return;
|
||
const b=button('Carregar mais',fn,'btn ghost');b.style.alignSelf='flex-start';b.style.marginTop='8px';container.append(b);
|
||
}
|
||
|
||
// Payments needing a person: paged, open or resolved (history).
|
||
let issueState='open', issueRows=[], issueTotal=0, issuePage=1, issueSize=20, issueLoading=0;
|
||
async function loadIssues(){
|
||
const token=++issueLoading;
|
||
const page=await api('/payment-events?'+new URLSearchParams({state:issueState,limit:String(issueSize),offset:String((issuePage-1)*issueSize)}));
|
||
if(token!==issueLoading)return;
|
||
issueRows=page.issues;issueTotal=page.total;
|
||
if(issuePage>1&&!issueRows.length&&issueTotal){issuePage=Math.ceil(issueTotal/issueSize);return loadIssues();}
|
||
renderIssues();
|
||
}
|
||
function renderIssues(){
|
||
const filters=node('div',undefined,'chips');filters.style.marginBottom='12px';
|
||
chips(filters,[['open','Abertos'],['resolved','Resolvidos'],['all','Todos']],issueState,key=>{issueState=key;issuePage=1;loadIssues().catch(e=>say(e.message,true));});
|
||
const list=node('div');
|
||
if(!issueRows.length)list.append(node('p',issueState==='resolved'?'Nenhum pagamento resolvido.':'Nenhum pagamento pendente.','faint'));
|
||
for(const issue of issueRows){
|
||
const box=node('div',undefined,'issue');
|
||
if(issue.resolved_at)box.classList.add('done');
|
||
box.append(issue.resolved_at?icon(ICON_OK):icon(ICON_WARN));box.firstChild.style.color=issue.resolved_at?'var(--ok)':'var(--warn)';
|
||
const text=node('div',undefined,'text');
|
||
text.append(node('b',(issue.amount_cents==null?'Pagamento sem valor informado':'Pagamento de '+money(issue.amount_cents))+': '+outcomeText(issue.outcome)),
|
||
node('span',issue.provider+' · evento '+issue.event_id+' · cotação '+(issue.reference||'—')+' · '+when(issue.received_at)));
|
||
if(issue.resolved_at){
|
||
text.append(node('span','Resolvido por '+issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution));
|
||
box.append(text);
|
||
}else{
|
||
const form=node('form');const note=node('input');note.placeholder='Resolução';note.setAttribute('aria-label','Resolução');note.required=true;note.minLength=3;note.maxLength=1000;
|
||
const save=node('button','Registrar resolução','btn warn');form.append(note,save);
|
||
form.onsubmit=async e=>{e.preventDefault();save.disabled=true;
|
||
try{await api('/payment-events/'+issue.id+'/resolve',{note:note.value});say('Resolução registrada.');await load();}
|
||
catch(error){say(error.message,true);save.disabled=false;}};
|
||
box.append(text,form);
|
||
}
|
||
list.append(box);
|
||
}
|
||
const bar=pager({page:issuePage,size:issueSize,total:issueTotal,noun:'pagamentos',
|
||
onPage:n=>{issuePage=n;loadIssues().catch(e=>say(e.message,true));},
|
||
onSize:n=>{issueSize=n;issuePage=1;loadIssues().catch(e=>say(e.message,true));}});
|
||
$('payments').replaceChildren(filters,list,bar);
|
||
}
|
||
|
||
// The integration send log: filtered and paged on the server.
|
||
let eventFilter={provider:'',status:'',event:'',order:''}, eventRows=[], eventTotal=0, eventPage=1, eventSize=20, eventLoading=0, eventTimer=null;
|
||
async function loadEvents(){
|
||
const token=++eventLoading;
|
||
const params=new URLSearchParams({limit:String(eventSize),offset:String((eventPage-1)*eventSize)});
|
||
for(const [key,value] of Object.entries(eventFilter))if(value)params.set(key,value);
|
||
const page=await api('/events?'+params);
|
||
if(token!==eventLoading)return;
|
||
eventRows=page.events;eventTotal=page.total;
|
||
if(eventPage>1&&!eventRows.length&&eventTotal){eventPage=Math.ceil(eventTotal/eventSize);return loadEvents();}
|
||
renderEvents();
|
||
}
|
||
function eventFilters(){
|
||
const bar=$('event-filters');if(bar.dataset.ready)return;bar.dataset.ready='1';
|
||
const select=(label,key,options)=>{
|
||
const field=node('label',undefined,'field');field.append(label);
|
||
const s=node('select');for(const [value,text] of options){const o=node('option',text);o.value=value;s.append(o);}
|
||
s.onchange=()=>{eventFilter[key]=s.value;eventPage=1;loadEvents().catch(e=>say(e.message,true));};
|
||
field.append(s);return field;
|
||
};
|
||
const order=node('label',undefined,'field');order.append('Pedido');
|
||
const input=node('input');input.type='number';input.min='1';input.placeholder='Nº';input.setAttribute('inputmode','numeric');
|
||
input.oninput=()=>{clearTimeout(eventTimer);eventTimer=setTimeout(()=>{eventFilter.order=input.value.trim();eventPage=1;loadEvents().catch(e=>say(e.message,true));},350);};
|
||
order.append(input);
|
||
bar.append(
|
||
select('Destino','provider',[['','Todos'],['tiny','Tiny'],['whatsapp','WhatsApp']]),
|
||
select('Situação','status',[['','Todas'],['delivered','Enviados'],['queued','Na fila'],['failing','Com erro']]),
|
||
select('Evento','event',[['','Todos'],...Object.entries(EVENTS)]),
|
||
order);
|
||
}
|
||
function eventResult(e){
|
||
const receipt=e.receipt||{};
|
||
if(e.delivered_at){
|
||
const situacao=receipt.situacao?' · '+receipt.situacao:'';
|
||
if(receipt.status==='created')return ['Criado no Tiny nº '+receipt.tiny_number+situacao,'good'];
|
||
if(receipt.status==='already-created')return ['Já existia no Tiny nº '+receipt.tiny_number+' (reenvio)'+situacao,'good'];
|
||
if(receipt.status==='status-updated')return ['Tiny nº '+receipt.tiny_number+situacao,'good'];
|
||
if(receipt.status==='status-unchanged')return ['Tiny nº '+receipt.tiny_number+' já estava'+situacao.replace(' · ',' em '),''];
|
||
if(receipt.status==='not-applicable')return ['Não se aplica ao Tiny',''];
|
||
return ['Registrado, sem envio',''];
|
||
}
|
||
if(e.last_error)return ['Nova tentativa · '+e.last_error+' (tentativa '+e.attempts+')','retry'];
|
||
return ['Na fila',''];
|
||
}
|
||
function renderEvents(){
|
||
const rows=eventRows.map(e=>{
|
||
const tr=node('tr');const [result,cls]=eventResult(e);
|
||
tr.append(node('td',when(e.delivered_at||e.available_at),'muted'),node('td','#'+e.payload.number,'mono'),
|
||
node('td',{tiny:'Tiny',whatsapp:'WhatsApp'}[e.provider]||e.provider),
|
||
node('td',EVENTS[e.payload.event]||e.payload.event),node('td',result,cls));
|
||
return tr;
|
||
});
|
||
if(!rows.length){const tr=node('tr');const td=node('td','Nenhum envio encontrado.','faint');td.colSpan=5;tr.append(td);rows.push(tr);}
|
||
$('events').replaceChildren(...rows);
|
||
$('events-more').replaceChildren(pager({page:eventPage,size:eventSize,total:eventTotal,noun:'envios',
|
||
onPage:n=>{eventPage=n;loadEvents().catch(e=>say(e.message,true));},
|
||
onSize:n=>{eventSize=n;eventPage=1;loadEvents().catch(e=>say(e.message,true));}}));
|
||
}
|
||
|
||
function renderIntegrations(){
|
||
const t=board.tiny||{};const cards=[];
|
||
if(!t.configured)cards.push(integration('Tiny','Não configurado','off','Credenciais ausentes no servidor.'));
|
||
else{
|
||
const connect=button(t.connected?'Reconectar':'Conectar Tiny',async()=>{const r=await api('/tiny/connect',{});location.href=r.url;},t.connected?'btn ghost':'btn');
|
||
const actions=[connect];
|
||
if(t.connected){
|
||
actions.unshift(button('Testar conexão',async()=>{const r=await api('/tiny/test',{});
|
||
say(r.ok?'Conexão com o Tiny ok: pedidos, contatos, os 4 produtos e a retirada conferidos.':'Tiny: '+Object.entries(r.results).filter(([,v])=>v!=='ok').map(([k,v])=>k+': '+v).join(' · '),!r.ok);}));}
|
||
cards.push(integration('Tiny',!t.connected?'Não conectado':t.problem?'Verificar':'Conectado',
|
||
t.connected&&!t.problem?'ok':'warn',tinyDetail(t),actions));
|
||
}
|
||
const mp=board.providers?.payment;
|
||
const mpActions=mp==='mercadopago'?[button('Verificar conta',async()=>{
|
||
const r=await api('/mercadopago/check',{});
|
||
const conta=r.account.error?'conta: '+r.account.error:'conta '+r.account.nickname+' ('+r.account.id+') · '+
|
||
(r.account.test_user?'usuário de teste':'não é usuário de teste');
|
||
const bin=Array.isArray(r.bin)?(r.bin.length?r.bin.map(o=>o.method+' '+o.type+' · '+o.issuer+' · até '+Math.max(...o.installments)+'x').join('; '):'cartão de teste não reconhecido'):'cartão: '+r.bin.error;
|
||
const w=r.webhooks||{};
|
||
const avisos='avisos nas últimas 24 h: '+w.accepted_24h+' aceitos, '+w.refused_24h+' recusados pela assinatura'+
|
||
(w.last?' · último em '+new Date(w.last.received_at).toLocaleString('pt-BR')+' ('+w.last.status+')':' · nenhum recebido ainda');
|
||
say('Mercado Pago: credencial '+(r.token==='test'?'de teste':'de produção')+' · '+conta+' · '+bin+' · '+avisos,false,60000);
|
||
},'btn ghost')]:[];
|
||
cards.push(integration('Mercado Pago',mp==='mercadopago'?'Ativo':'Não configurado',mp==='mercadopago'?'ok':'off',
|
||
mp==='mercadopago'?'PIX e cartão ativos.':'Aguardando credenciais.',mpActions));
|
||
const fr=board.providers?.freight||{};
|
||
const kg=v=>String(v).replace('.',',')+' kg';
|
||
// Jadlog charges the larger of the real and the cubed weight: without the
|
||
// box and the contract's factor, a light big box is quoted below its price.
|
||
const caixa=fr.box_cm?' Caixa '+fr.box_cm.map(n=>String(n).replace('.',',')).join(' × ')+' cm a '+
|
||
String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'+
|
||
(fr.metres_per_box?', até '+String(fr.metres_per_box).replace('.',',')+' m por caixa':'')+'; vale o maior dos dois pesos.'
|
||
:' Cubagem não configurada: a cotação usa só o peso real, e a Jadlog pode cobrar pelo tamanho da caixa.';
|
||
cards.push(fr.provider==='jadlog'
|
||
? integration('Frete',fr.box_cm?'Ativo':'Verificar',fr.box_cm?'ok':'warn','Entrega pela Jadlog e retirada em Franca. Pacote: '+kg(fr.base_kg)+
|
||
' + '+kg(fr.per_metre_kg)+' por metro.'+caixa+' Prazo da Jadlog + '+fr.production_days+' dia(s) de produção.')
|
||
: integration('Frete','Não configurado','off','Somente retirada.'));
|
||
cards.push(integration('WhatsApp','Não configurado','off','Mensagens registradas, sem envio.'));
|
||
const bk=board.providers?.backup||{};
|
||
const ontem=bk.last_ok&&Date.now()-new Date(bk.last_ok)<26*3600e3;
|
||
const tam=bk.bytes?' · '+(bk.bytes<1048576?Math.max(1,Math.round(bk.bytes/1024))+' KB':(bk.bytes/1048576).toFixed(1).replace('.',',')+' MB'):'';
|
||
cards.push(integration('Backup do banco',!bk.last_ok&&!bk.failed?'Não configurado':ontem&&!bk.failed?'Em dia':'Verificar',
|
||
!bk.last_ok&&!bk.failed?'off':ontem&&!bk.failed?'ok':'warn',
|
||
(bk.last_ok?'Último backup em '+when(bk.last_ok)+tam+'.':'Nenhum backup feito ainda.')+
|
||
(bk.failed?' A última tentativa falhou ('+when(bk.failed_at)+'): '+bk.failed:'')+' Cópia diária, criptografada, fora do servidor.'));
|
||
$('integrations').replaceChildren(...cards);
|
||
eventFilters();
|
||
}
|
||
|
||
// ---- Wiring --------------------------------------------------------------
|
||
|
||
for(const b of document.querySelectorAll('[data-tab]'))b.onclick=()=>showTab(b.dataset.tab);
|
||
$('quote-q').oninput=e=>{clearTimeout(quoteTimer);quoteTimer=setTimeout(()=>{
|
||
quoteQuery=e.target.value.trim();quotePage=1;loadQuotes().catch(err=>say(err.message,true));},300);};
|
||
|
||
// ---- Search: orders (any stage) and unpaid quotes ---------------------------
|
||
|
||
let searchTimer=null, searchToken=0, searchHits=[], searchAt=-1;
|
||
function closeSearch(){$('search-results').hidden=true;$('search').setAttribute('aria-expanded','false');searchAt=-1;}
|
||
async function runSearch(text){
|
||
const token=++searchToken;
|
||
const result=absorb(await api('/search?'+new URLSearchParams({q:text})));
|
||
if(token!==searchToken||$('search').value.trim()!==text)return;
|
||
const box=$('search-results');searchHits=[];searchAt=-1;
|
||
const parts=[];
|
||
for(const [title,rows,make] of [['Pedidos',result.orders,orderHit],['Cotações',result.quotes,quoteHit]]){
|
||
if(!rows.length)continue;
|
||
parts.push(node('div',title+' · '+rows.length,'rgroup'));
|
||
for(const row of rows){const hit=make(row);hit.el.id='hit-'+searchHits.length;searchHits.push(hit);parts.push(hit.el);}
|
||
}
|
||
if(!searchHits.length)parts.push(node('p','Nada encontrado para “'+text+'”.','rempty'));
|
||
parts.push(node('div','↑ ↓ para escolher · Enter abre · Esc fecha · busca por e-mail, CNPJ, WhatsApp ou nº do pedido','rhelp'));
|
||
box.replaceChildren(...parts);box.hidden=false;$('search').setAttribute('aria-expanded','true');
|
||
}
|
||
function hitRow(items,title,sub,meta,badge,color,open){
|
||
const el=node('button',undefined,'rhit');el.type='button';el.setAttribute('role','option');el.setAttribute('aria-selected','false');
|
||
const text=node('div',undefined,'rtext');const line=node('div');line.append(node('b',title),node('span',sub));
|
||
text.append(line,node('span',meta,'rmeta'));
|
||
const tag=node('span',badge,'rbadge');if(color)tag.style.setProperty('--c',color);
|
||
el.append(artBox(items,'rart'),text,tag);
|
||
el.onmousedown=e=>e.preventDefault();
|
||
el.onclick=()=>{closeSearch();open();};
|
||
return {el,open};
|
||
}
|
||
function orderHit(order){
|
||
const s=order.snapshot;
|
||
return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title,
|
||
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(s.destination?'Entrega':'Retirada')+' · pago '+when(order.created_at),
|
||
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'var(--bad)':STAGE_COLORS[order.state],()=>{
|
||
// An older finished order is not on the board yet: it joins, like "Carregar mais".
|
||
if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);}
|
||
showTab('board');openPanel(order.id);});
|
||
}
|
||
function quoteHit(q){
|
||
return hitRow(q.draft.items,q.approved?money(q.approved.total_cents):'Cotação '+q.id.slice(0,8),buyer(q.draft).title,
|
||
q.draft.items.map(i=>SHORT[i.mode]).join(' + ')+' · '+metres(quoteMetres(q))+' · '+ago(q.created_at),
|
||
q.approved?'Aguardando pagamento':'A revisar',q.approved?'':'var(--accent)',()=>{
|
||
// Opens Cotações filtered to this customer, with this quote selected.
|
||
quoteKind=q.approved?'approved':'pending';quoteQuery=q.draft.customer.mail;$('quote-q').value=quoteQuery;
|
||
quoteProduct=quoteLayout=quoteFlag='';quotePage=1;currentQuote=q;showTab('quotes');});
|
||
}
|
||
$('search').oninput=e=>{
|
||
const text=e.target.value.trim();clearTimeout(searchTimer);
|
||
if(text.length<2){searchToken++;closeSearch();return;}
|
||
searchTimer=setTimeout(()=>runSearch(text).catch(err=>say(err.message,true)),250);
|
||
};
|
||
$('search').onkeydown=e=>{
|
||
if(e.key==='Escape'){e.stopPropagation();closeSearch();return;}
|
||
if($('search-results').hidden||!searchHits.length)return;
|
||
if(e.key==='ArrowDown'||e.key==='ArrowUp'){
|
||
e.preventDefault();searchAt=(searchAt+(e.key==='ArrowDown'?1:-1)+searchHits.length)%searchHits.length;
|
||
searchHits.forEach((h,i)=>h.el.setAttribute('aria-selected',String(i===searchAt)));
|
||
$('search').setAttribute('aria-activedescendant',searchHits[searchAt].el.id);searchHits[searchAt].el.scrollIntoView({block:'nearest'});
|
||
}
|
||
if(e.key==='Enter'){e.preventDefault();const hit=searchHits[Math.max(0,searchAt)];closeSearch();hit.open();}
|
||
};
|
||
$('search').onblur=()=>setTimeout(closeSearch,150);
|
||
$('search').onfocus=()=>{if($('search').value.trim().length>=2&&searchHits.length){$('search-results').hidden=false;$('search').setAttribute('aria-expanded','true');}};
|
||
// "/" jumps to the search, as the field shows, unless typing somewhere else.
|
||
document.addEventListener('keydown',e=>{
|
||
if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey)return;
|
||
const t=e.target;if(t.closest&&t.closest('input,textarea,select,[contenteditable="true"]'))return;
|
||
if($('app').hidden)return;e.preventDefault();$('search').focus();
|
||
});
|
||
$('login').onsubmit=async e=>{e.preventDefault();try{await api('/login',{email:$('email').value,password:$('password').value});await load();}catch(error){say(error.message,true);}finally{$('password').value='';}};
|
||
$('logout').onclick=async()=>{await api('/logout',{});for(const key of Object.keys(localStorage))if(key.startsWith('dtf-'))localStorage.removeItem(key);location.reload();};
|
||
$('refresh').onclick=()=>load();
|
||
|
||
// ---- Refreshing by itself --------------------------------------------------
|
||
|
||
// New orders and quotes to review since the last load: a notice, and the
|
||
// count in the tab's title until the operator looks at the tab.
|
||
function noticeNew(quiet){
|
||
const orders=new Set(board.orders.map(o=>o.id));
|
||
const fresh=seenOrders?board.orders.filter(o=>!seenOrders.has(o.id)&&o.state==='rec'&&!o.cancelled_at):[];
|
||
const reviews=seenPending===null?0:Math.max(0,board.pending_total-seenPending);
|
||
seenOrders=orders;seenPending=board.pending_total;
|
||
if(!fresh.length&&!reviews)return;
|
||
const parts=[];
|
||
if(fresh.length)parts.push(fresh.length===1?'Novo pedido #'+fresh[0].number:fresh.length+' pedidos novos');
|
||
if(reviews)parts.push(reviews===1?'1 cotação nova para revisar':reviews+' cotações novas para revisar');
|
||
say(parts.join(' · '),false,10000);
|
||
if(document.hidden||quiet){unseen+=fresh.length+reviews;document.title='('+unseen+') Kanban DTF';}
|
||
}
|
||
document.addEventListener('visibilitychange',()=>{if(!document.hidden){unseen=0;document.title='Kanban DTF';}});
|
||
addEventListener('focus',()=>{unseen=0;document.title='Kanban DTF';});
|
||
|
||
// Every N seconds, chosen beside "Atualizar" and remembered by this browser.
|
||
// Never under the operator's hands: not while typing, dragging or with an
|
||
// order open. With the Kanban's tab hidden it still looks, at most once a
|
||
// minute, so the tab's title can say a new order arrived.
|
||
let autoTimer=null, lastAuto=0;
|
||
function busy(){
|
||
const a=document.activeElement;
|
||
const typing=!!(a&&a.matches&&a.matches('input,textarea,select')&&a.id!=='refresh-every');
|
||
return $('app').hidden||!!dragging||!$('drawer').hidden||typing;
|
||
}
|
||
function autoRefresh(){
|
||
if(busy())return;
|
||
if(document.hidden&&Date.now()-lastAuto<60000)return;
|
||
lastAuto=Date.now();
|
||
load(true).catch(()=>{});
|
||
}
|
||
function scheduleAuto(){
|
||
clearInterval(autoTimer);
|
||
const secs=Number($('refresh-every').value);
|
||
if(secs)autoTimer=setInterval(autoRefresh,secs*1000);
|
||
}
|
||
(()=>{
|
||
let saved='30';
|
||
try{saved=localStorage.getItem('dtf-refresh-every')??'30';}catch(_){}
|
||
$('refresh-every').value=[...$('refresh-every').options].some(o=>o.value===saved)?saved:'30';
|
||
$('refresh-every').onchange=()=>{
|
||
try{localStorage.setItem('dtf-refresh-every',$('refresh-every').value);}catch(_){}
|
||
scheduleAuto();$('refresh-every').blur();
|
||
};
|
||
scheduleAuto();
|
||
})();
|
||
load();
|