Compare commits

..

4 Commits

Author SHA1 Message Date
Cauê Faleiros
d6c80ff447 Merge 503 during a database restart (DTF-API-8, 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 7m6s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m44s
2026-11-16 09:46:37 -03:00
Cauê Faleiros
4e6f96bfe2 Merge board and order panel files (plan 007e) 2026-11-16 09:46:37 -03:00
Cauê Faleiros
ee772a43ff refactor: the production board and the order panel in files of their own
Plan 007e (Critical Corrections 7, last step; layout Phase D step 1):
web/kanban-board.js holds the board and the phone screens, and
web/kanban-order.js the order panel, its dialogs, the final files and
Abrir e conferir, moved verbatim from kanban.js (now 952 lines). The
browser test also walks the phone board. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 09:46:36 -03:00
Cauê Faleiros
bcba1fbe67 fix: a request during a database restart answers 503, and the logs stay quiet
Sentry DTF-API-8/9 (stack restart, 16/11 09:15): the startup retry kept
the API up, but a board request in the ~7 s without the database got a
500, and the render thread logged its error every 2 s. A request that
hits psycopg.OperationalError now answers 503 "O servidor está
reiniciando" with Retry-After (the web does not report it); the render
thread warns once per outage and backs off; the worker's first outage
line and the audit's connection outage are warnings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 09:32:50 -03:00
11 changed files with 1801 additions and 1717 deletions

View File

@@ -9,7 +9,8 @@ import logging
import time import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI import psycopg
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware from starlette.middleware.trustedhost import TrustedHostMiddleware
@@ -52,6 +53,17 @@ async def lifespan(app):
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None) app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS) app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
# The seconds a restart takes the database away (Sentry DTF-API-9): the
# request is answered "try again" instead of a 500, and only a warning is
# logged (Sentry takes errors). The page retries by itself or on reload.
RESTARTING = 'O servidor está reiniciando. Tente de novo em alguns segundos.'
@app.exception_handler(psycopg.OperationalError)
async def database_unavailable(request: Request, exc):
logging.warning('Database unavailable for %s %s: %s', request.method, request.url.path, exc)
return JSONResponse({'detail': RESTARTING}, status_code=503, headers={'Retry-After': '5'})
@app.middleware('http') @app.middleware('http')
async def safe_headers(request, call_next): async def safe_headers(request, call_next):
if request.method not in ('GET','HEAD','OPTIONS'): if request.method not in ('GET','HEAD','OPTIONS'):

View File

@@ -4,6 +4,8 @@ import os
import secrets import secrets
import logging import logging
import json import json
import psycopg
import sys
import time import time
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
@@ -95,7 +97,9 @@ def audit(event, c=None, **fields):
now = time.monotonic() now = time.monotonic()
if _persistence_error_at is None or now-_persistence_error_at >= 60: if _persistence_error_at is None or now-_persistence_error_at >= 60:
_persistence_error_at = now _persistence_error_at = now
logging.getLogger('dtf.security').error('Security event persistence unavailable') log = logging.getLogger('dtf.security')
(log.warning if isinstance(sys.exc_info()[1], psycopg.OperationalError) else log.error)(
'Security event persistence unavailable')
def rate_limit(scope, identity, limit, seconds=900): def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest() key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()

View File

@@ -30,6 +30,7 @@ from decimal import Decimal
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5 from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
import psycopg
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from PIL import Image from PIL import Image
@@ -380,10 +381,22 @@ def finish(job, status, detail):
def render_loop(storage): def render_loop(storage):
down_since, delay = None, 2
while True: while True:
try: try:
if render_one(storage): if render_one(storage):
continue continue
except psycopg.OperationalError as exc:
# A restart takes the database away for seconds: say so once.
if down_since is None:
down_since = time.monotonic()
logging.warning('Print render worker: database unavailable, retrying: %s', exc)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception: except Exception:
logging.exception('Print render worker tick failed') logging.exception('Print render worker tick failed')
if down_since is not None:
logging.info('Print render worker: database back after %s s', int(time.monotonic() - down_since))
down_since, delay = None, 2
time.sleep(2) time.sleep(2)

View File

@@ -146,7 +146,7 @@ def loop():
except psycopg.OperationalError as exc: except psycopg.OperationalError as exc:
if db_down_since is None: if db_down_since is None:
db_down_since = time.monotonic() db_down_since = time.monotonic()
logging.error('Database unavailable, retrying: %s', exc) logging.warning('Database unavailable, retrying: %s', exc)
else: else:
logging.debug('Database still unavailable, retrying in %s s', delay) logging.debug('Database still unavailable, retrying in %s s', delay)
time.sleep(delay) time.sleep(delay)

View File

@@ -369,6 +369,19 @@ try{
await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab'); await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab');
await kanban.click('[data-tab="integrations"]'); await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab'); await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab');
// The phone board lives in its own file now: open its Mais and filters.
await kanban.call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
await waitFor(()=>kanban.eval('PHONE.matches'),'phone board');
await kanban.click('#more-nav');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone menu');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone menu closed');
await kanban.click('#filter-open');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone filters');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone filters closed');
await kanban.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
await waitFor(()=>kanban.eval('!PHONE.matches'),'desktop board again');
// A guest sees the order paid in this browser; creating an account keeps it. // A guest sees the order paid in this browser; creating an account keeps it.
const portal=await page(siteOrigin+'/conta/pedidos?order='+oid); const portal=await page(siteOrigin+'/conta/pedidos?order='+oid);
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking'); await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking');

View File

@@ -46,13 +46,14 @@ class WorkerDatabaseOutageTest(unittest.TestCase):
mock.patch.object(worker.mail, 'send_pending'), \ mock.patch.object(worker.mail, 'send_pending'), \
mock.patch.object(worker.time, 'sleep', mock.patch.object(worker.time, 'sleep',
side_effect=[None, None, None, self.StopLoop]) as sleep, \ side_effect=[None, None, None, self.StopLoop]) as sleep, \
mock.patch.object(worker.logging, 'error') as error, \ mock.patch.object(worker.logging, 'warning') as warning, \
mock.patch.object(worker.logging, 'info') as info, \ mock.patch.object(worker.logging, 'info') as info, \
mock.patch.object(worker.logging, 'debug') as debug: mock.patch.object(worker.logging, 'debug') as debug:
with self.assertRaises(self.StopLoop): with self.assertRaises(self.StopLoop):
worker.loop() worker.loop()
self.assertEqual(error.call_count, 1) # A warning, not an error: a restart is expected (Sentry DTF-API-8).
self.assertIn('Database unavailable', error.call_args[0][0]) self.assertEqual(warning.call_count, 1)
self.assertIn('Database unavailable', warning.call_args[0][0])
self.assertEqual(info.call_count, 1) self.assertEqual(info.call_count, 1)
self.assertIn('Database back after', info.call_args[0][0]) self.assertIn('Database back after', info.call_args[0][0])
self.assertEqual(debug.call_count, 2) self.assertEqual(debug.call_count, 2)
@@ -76,8 +77,32 @@ class AuditPersistenceOutageTest(unittest.TestCase):
auth.audit('first') auth.audit('first')
auth.audit('second') auth.audit('second')
auth.audit('third') auth.audit('third')
self.assertEqual(error.call_count, 2) # A connection outage: the event lines and, once a minute, a warning.
self.assertEqual(warning.call_count, 3) self.assertEqual(error.call_count, 0)
self.assertEqual(warning.call_count, 5)
def test_any_other_persistence_failure_is_an_error(self):
logger = auth.logging.getLogger('dtf.security')
with mock.patch.object(auth, 'connect', side_effect=RuntimeError('bad table')), \
mock.patch.object(auth.time, 'monotonic', return_value=100.0), \
mock.patch.object(logger, 'error') as error, \
mock.patch.object(logger, 'warning'):
auth.audit('first')
self.assertEqual(error.call_count, 1)
class RequestDuringOutageTest(unittest.TestCase):
def test_a_request_gets_503_with_retry_after(self):
"""Sentry DTF-API-9: the board answered 500 while the database restarted."""
import asyncio
from app import app as module
request = mock.Mock(method='GET', url=mock.Mock(path='/api/operator/board'))
with mock.patch.object(module.logging, 'warning') as warning:
response = asyncio.run(module.database_unavailable(request, psycopg.OperationalError('down')))
self.assertEqual(response.status_code, 503)
self.assertEqual(response.headers['retry-after'], '5')
self.assertIn(b'reiniciando', response.body)
self.assertEqual(warning.call_count, 1)
if __name__ == '__main__': if __name__ == '__main__':

607
web/kanban-board.js Normal file
View File

@@ -0,0 +1,607 @@
/* Kanban DTF: the production board, its filters and lanes, and the phone
board (fronts 5/11 and the design canvas' phone screens). Loaded after
kanban.js, which defines $, api, node, button, svgIcon, IC, badge, money,
when, ago, metres, plural, say, may, mayMove, mayReorder, mayAct, myMachine,
isMine, board, boardFilter, tab, load, render, download, downloadQueue,
field, formDialog, stageLimitsDialog, absorb, olderFinished, buyer, artBox,
lowestGrade, cm, SHORT and ME. */
// ---- Production board ----------------------------------------------------
function printState(order){
if(order.state==='imp'||order.state==='rev')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==='failed'||r.timed_out))return {text:'Falhou ao gerar',tone:'warn'};
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=>!!order.late;
// "Aguardando contato": a word with the customer is needed before printing.
// A mark on the card, not a stage; a finished order no longer needs it.
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
const PROOF_ABOVE_METRES=10;
const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.';
const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES;
const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent;
// The proof card (app/proof.py): the order's own card waits outside the queue
// for its answer; an order from before the cards has none.
const waitingProof=order=>!!order.proof_card&&!order.proof_card.proof_result&&!order.proof_ok_at;
const proofRejected=order=>order.proof_card?.proof_result==='rejected'&&!order.proof_ok_at;
async function proofAnswer(order,result,reason=''){
await api('/orders/'+order.id+'/proof-answer',{result,reason});await load();
say(result==='ok'?'Prova OK: o pedido #'+order.proof_parent.number+' entra na fila.':'Prova reprovada: o pedido #'+order.proof_parent.number+' voltou para Arte recebida.');
}
function proofReject(order){
const reason=node('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=3;
formDialog('Prova reprovada',{host:$('drawer'),label:'Reprovar a prova',tone:'red',
text:'O pedido #'+order.proof_parent.number+' volta para Arte recebida com o motivo, e este card de prova encerra.',
fields:[field('Motivo',reason)],onsave:async()=>{await proofAnswer(order,'rejected',reason.value);}});
}
const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte que o cliente mandou.';
// Mirrored by the customer (UV only, web/site-pdf.js): the room checks it before printing.
const mirroredItem=item=>!!item.production?.sources?.some(source=>source.mirrored);
const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir';
// Residue dots under 2 mm the customer accepted printing (Dropstar, 2026-10-29).
const residueNote=item=>{const many=item.residue_accepted>1;
return item.residue_accepted+(many?' pontos menores':' ponto menor')+' que 2 mm, que '+(many?'podem':'pode')+' se perder no recorte';};
const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imprimir com '+residueNote(item));
// Two places per machine in Imprimindo (app/machines.py): the first to come
// in is printing, the next is being ripped meanwhile.
const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'],
ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']};
// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30):
// "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from
// the hot folder while the one before it prints.
function partsStep(order){
const hot=order.hot;if(!hot||hot.parts<2)return null;
const n=hot.parts, t=hot.taken;
if(!t)return ['Parte 1/'+n+' na hot folder','wait'];
if(t===1)return ['Parte 1/'+n+' ripando','rip'];
return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live'];
}
async function proofOk(order){
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
}
// Where an order came from (Dropstar's rule D-21): every card says it.
const ORIGINS={site:'Site',dropflow:'Dropflow',atendimento:'Atendimento'};
const ORIGIN_NOTE='Origem do pedido';
const originTag=order=>{const t=node('span',ORIGINS[order.origin]||order.origin,'origin');t.title=ORIGIN_NOTE;return t;};
// The board's filters: one choice per kind, and the kinds combine (Têxtil on
// máquina2, waiting for contact). An empty choice is "all".
const FILTER_TESTS={
site:o=>o.origin==='site',
dropflow:o=>o.origin==='dropflow',
atendimento:o=>o.origin==='atendimento',
textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'),
uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'),
entrega:o=>!!o.snapshot.destination,
retirada:o=>!o.snapshot.destination,
parados:stalled,
atrasados:stalled,
contato:waitingContact,
prova:proofPending,
manual:o=>['rec','tra'].includes(o.state)&&!finalDone(o)&&(o.print_files||[]).some(r=>
(r.status==='manual'||r.status==='failed')&&!(o.corrections||[]).some(f=>f.item_index===r.item_index)),
};
function matches(order,f=boardFilter){
// A cancelled order shows only under "Cancelados", and only there.
if(!!order.cancelled_at!==(f.status==='cancelados'))return false;
return Object.values(f).every(key=>!key||key==='cancelados'||
(key.startsWith('m:')?order.machine?.id===key.slice(2):FILTER_TESTS[key](order)));
}
// What each choice would show: orders in progress, or every cancelled one.
const filterCount=f=>board.orders.filter(o=>(f.status==='cancelados'||o.state!=='fin')&&matches(o,f)).length;
// The kinds of filter: [value, label in the panel, label on the tag]. The
// product is the segment beside the button, not in the panel.
function filterKinds(){
const kinds=[
{key:'delivery',label:'Envio',options:[['entrega','Entrega'],['retirada','Retirada']]},
{key:'origin',label:'Origem',options:Object.entries(ORIGINS)},
{key:'status',label:'Situação',options:[['atrasados','Fora do tempo aceitável','Atrasados'],
['contato','Aguardando contato'],['prova','Prova a conferir'],['manual','Preparar à mão'],['cancelados','Cancelados']]}];
// A machine, when there is more than one to tell apart.
const machines=(board.machines||[]).filter(m=>m.active||m.open_orders);
if(machines.length>1)kinds.unshift({key:'machine',label:'Máquina',options:machines.map(m=>
['m:'+m.id,m.name+(m.limit_metres&&m.open_metres>m.limit_metres?' · acima do limite':''),m.name])});
return kinds;
}
const PRODUCTS=[['','Todos'],['textil','Têxtil'],['uv','UV']];
const xIcon=()=>svgIcon(IC.close,'i s');
function openFilters(){
const pop=$('filter-pop');
const close=node('button',undefined,'btn sq ghost right');close.type='button';close.setAttribute('aria-label','Fechar filtros');
close.append(svgIcon(IC.close,'i m'));close.onclick=closeFilters;
const head=node('div',undefined,'pophead');head.append(node('b','Filtros'),close);
const groups=filterKinds().map(kind=>{
const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts');
for(const [value,text] of kind.options){
const b=node('button',text,'fopt');b.type='button';b.dataset.kind=kind.key;b.dataset.value=value;
b.append(node('span','','n'));
// A second click on the choice in use takes it off.
b.onclick=()=>{boardFilter[kind.key]=boardFilter[kind.key]===value?'':value;renderBoard();};
opts.append(b);
}
group.append(node('span',kind.label),opts);return group;
});
const clear=node('button','Limpar filtros','btn ghost');clear.type='button';clear.onclick=clearFilters;
const foot=node('div',undefined,'popfoot');foot.append(clear,node('span','','lbl right'));
pop.replaceChildren(head,...groups,foot);pop.hidden=false;$('filter-btn').setAttribute('aria-expanded','true');
filterCounts();pop.querySelector('.fopt')?.focus();
}
function closeFilters(){$('filter-pop').hidden=true;$('filter-btn').setAttribute('aria-expanded','false');}
function clearFilters(){for(const key in boardFilter)if(key!=='product')boardFilter[key]='';renderBoard();}
// Each choice says how many orders it would show with the others kept.
function filterCounts(){
const pop=$('filter-pop');
for(const b of pop.querySelectorAll('.fopt')){
b.classList.toggle('on',boardFilter[b.dataset.kind]===b.dataset.value);
b.setAttribute('aria-pressed',String(boardFilter[b.dataset.kind]===b.dataset.value));
b.querySelector('.n').textContent=String(filterCount({...boardFilter,[b.dataset.kind]:b.dataset.value}));
}
const shown=filterCount(boardFilter);
pop.querySelector('.popfoot .lbl').textContent=plural(shown,'pedido','pedidos');
}
// The product segment, the filters in use as tags beside the button, and the
// button's count.
function renderFilters(){
const kinds=filterKinds();
// A choice that is gone (a machine deleted or switched off) is dropped.
for(const key in boardFilter){if(key==='product')continue;const kind=kinds.find(k=>k.key===key);
if(boardFilter[key]&&!kind?.options.some(([value])=>value===boardFilter[key]))boardFilter[key]='';}
$('product-seg').replaceChildren(...PRODUCTS.map(([value,text])=>{
const b=node('button',text,boardFilter.product===value?'on':'');b.type='button';
b.setAttribute('aria-pressed',String(boardFilter.product===value));
b.append(node('span',String(filterCount({...boardFilter,product:value})),'n'));
b.onclick=()=>{boardFilter.product=value;renderBoard();};return b;}));
const used=kinds.filter(k=>boardFilter[k.key]);
const tags=used.map(kind=>{
const [,text,tag]=kind.options.find(([value])=>value===boardFilter[kind.key]);
const b=node('button',tag||text,'ftag');b.type='button';
b.setAttribute('aria-label','Tirar o filtro '+(tag||text));
const x=node('span',undefined,'x');x.append(xIcon());b.append(x);
b.onclick=()=>{boardFilter[kind.key]='';renderBoard();};return b;});
if(used.length>1){const all=node('button','Limpar','btn ghost');all.type='button';all.onclick=clearFilters;tags.push(all);}
$('filter-tags').replaceChildren(...tags);
$('filter-count').hidden=!used.length;$('filter-count').textContent=String(used.length);
const all=used.length+(boardFilter.product?1:0);$('filter-dot').hidden=!all;$('filter-dot').textContent=String(all);
$('filter-btn').classList.toggle('on',used.length>0);
if(!$('filter-pop').hidden)filterCounts();
}
// Each column's mark (the design canvas): what happens in that stage.
const GLYPH={
rec:'M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32Zm0,16V152h-28.7A15.86,15.86,0,0,0,168,156.69L148.69,176H107.31L88,156.69A15.86,15.86,0,0,0,76.69,152H48V48Zm0,160H48V168H76.69L96,187.31A15.86,15.86,0,0,0,107.31,192h41.38A15.86,15.86,0,0,0,160,187.31L179.31,168H208v40ZM90.34,125.66a8,8,0,0,1,11.32-11.32L120,132.69V72a8,8,0,0,1,16,0v60.69l18.34-18.35a8,8,0,0,1,11.32,11.32l-32,32a8,8,0,0,1-11.32,0Z',
tra:'M224,128a8,8,0,0,1-8,8H128a8,8,0,0,1,0-16h88A8,8,0,0,1,224,128ZM128,72h88a8,8,0,0,0,0-16H128a8,8,0,0,0,0,16Zm88,112H128a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16ZM82.34,42.34,56,68.69,45.66,58.34A8,8,0,0,0,34.34,69.66l16,16a8,8,0,0,0,11.32,0l32-32A8,8,0,0,0,82.34,42.34Zm0,64L56,132.69,45.66,122.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Zm0,64L56,196.69,45.66,186.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Z',
imp:'M214.67,72H200V40a8,8,0,0,0-8-8H64a8,8,0,0,0-8,8V72H41.33C27.36,72,16,82.77,16,96v80a8,8,0,0,0,8,8H56v32a8,8,0,0,0,8,8H192a8,8,0,0,0,8-8V184h32a8,8,0,0,0,8-8V96C240,82.77,228.64,72,214.67,72ZM72,48H184V72H72ZM184,208H72V160H184Zm40-40H200V152a8,8,0,0,0-8-8H64a8,8,0,0,0-8,8v16H32V96c0-4.41,4.19-8,9.33-8H214.67c5.14,0,9.33,3.59,9.33,8Zm-24-52a12,12,0,1,1-12-12A12,12,0,0,1,200,116Z',
cor:'M232,144a64.07,64.07,0,0,1-64,64H80a8,8,0,0,1,0-16h88a48,48,0,0,0,0-96H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48A8,8,0,0,1,85.66,45.66L51.31,80H168A64.07,64.07,0,0,1,232,144Z',
rev:'M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z',
fin:'M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z'};
const orderMetres=o=>o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0);
// On a phone the board shows one stage at a time, picked from the chips above it.
let phoneCol='rec';
// Atrasados (front 11): the cards past the stage limit, with the person
// responsible for that column, above the board.
function renderLatebar(){
const bar=$('latebar');
// The top strip is for production delays. A pickup waiting in Finalizado
// keeps its yellow/red card and is counted in Números; it does not push
// every historical finished order across the top of the board.
const late=board.orders.filter(o=>!o.cancelled_at&&!isTest(o)&&o.late&&o.state!=='fin')
.sort((a,b)=>(b.state_hours||0)-(a.state_hours||0));
if(!late.length){bar.hidden=true;bar.replaceChildren();return;}
bar.hidden=false;
const head=node('b','Atrasados ('+late.length+')');bar.replaceChildren(head);
late.slice(0,10).forEach(o=>{
const chip=node('button',undefined,'latechip'+(o.late==='bad'?' bad':''));
chip.type='button';chip.append(node('i'),node('span','#'+o.number+' · '+board.states[o.state]));
chip.title=(o.state_hours??'?')+' h nesta etapa · limite '+(o.limit_hours??'?')+
' h · responsável: '+(o.limit_by||'—');
chip.onclick=()=>openPanel(o.id);bar.append(chip);
});
if(late.length>10)bar.append(node('span','+'+(late.length-10),'lbl'));
if(may('manage'))bar.append(button('Editar tempos',()=>stageLimitsDialog(),'btn ghost'));
}
function renderBoard(){
renderLatebar();
renderFilters();
const active=board.orders.filter(o=>['rec','tra','imp'].includes(o.state)&&!o.cancelled_at);
const open=board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length;
$('board-summary').textContent=plural(open,'pedido','pedidos')+', '+metres(active.reduce((s,o)=>s+orderMetres(o),0))+' em produção';
const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product;
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title);
// Working columns are queues; Finalizado shows the most recently ready order first.
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin'
? new Date(b.finished_at||b.updated_at)-new Date(a.finished_at||a.updated_at)||b.id.localeCompare(a.id)
: queueKey(a)-queueKey(b)||a.number-b.number);
const head=node('header',undefined,'colhead');
head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')));
const text=node('span',undefined,'coltx');text.append(node('h2',title));
if(state!=='fin')text.append(node('span',orders.length?metres(orders.reduce((s,o)=>s+orderMetres(o),0)):'vazio','colm'));
head.append(text);
// The print queue's files, all at once, to import into FlexiPRINT.
if(state==='tra'&&may('print')&&orders.length){
const all=node('button',undefined,'colbtn tip-l');all.type='button';all.setAttribute('aria-label','Baixar os arquivos da fila');
all.dataset.tip='Baixar os arquivos finais de todos os pedidos da fila, para o FlexiPRINT';all.append(svgIcon(IC.download,'i m'));
all.onclick=async()=>{all.disabled=true;try{await downloadQueue();}catch(e){say(e.message,true);}finally{all.disabled=false;}};
head.append(all);
}
// Finished orders are a recent window, not the whole history: the count is the whole.
head.append(node('span',String(state==='fin'&&!filtered?Math.max(board.finished_total||0,orders.length):orders.length),'coln'));
column.append(head);
// The phone's line over the cards: this stage's metres and the session's machine.
const sum=node('div',undefined,'msum');const total=node('span');
total.append(node('b',state==='fin'?plural(orders.length,'pedido','pedidos'):metres(orders.reduce((t,o)=>t+orderMetres(o),0))),state==='fin'?' recentes':' nesta etapa');
sum.append(total);
if(myMachine()){const m=node('span',undefined,'right mcell');m.append(node('i',undefined,'mdot'),'Máquina ',node('b',myMachine().name));sum.append(m);}
column.append(sum);
if(state==='tra'&&may('print')&&orders.length){
const dl=button('Baixar os arquivos da fila',downloadQueue,'btn mdl');dl.prepend(svgIcon(IC.download,'i m'));column.append(dl);}
if(state==='imp')column.append(...printingLanes(orders));
else if(state==='fin')column.append(...orders.map(miniCard));
else column.append(...orders.map((o,i)=>card(o,state==='tra'?queuePlace(o,orders):null)));
if(state==='fin'&&finishedMore&&!filtered){
const left=Math.max(0,(board.finished_total||0)-orders.length);
const more=node('button',left>50?'Ver mais 50 anteriores':left?'Ver os '+left+' anteriores':'Ver anteriores','moreold');more.type='button';
more.onclick=async()=>{more.disabled=true;try{await loadOlderFinished();}catch(e){say(e.message,true);more.disabled=false;}};
column.append(more);
}
// 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'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;}
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');
if(state==='imp')markLane(column,laneAt(column,e.clientY));};
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}};
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain'));
const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null);
if(!order)return;
try{
if(order.state!==state)await (state==='imp'?pullTo(order,machine):move(order,state,'',machine));
else if(state!=='fin')await reorder(order,column,e.clientY);
}catch(error){say(error.message,true);}
finally{clearDrop();}};
return column;
}));
const cols=[...$('kan').children];
if(!board.states[phoneCol])phoneCol='rec';
$('col-tabs').replaceChildren(...cols.map(col=>{
const st=col.dataset.state, on=st===phoneCol;
const b=node('button',undefined,'mtab'+(on?' on':''));b.type='button';b.setAttribute('role','tab');b.setAttribute('aria-selected',String(on));
b.append(svgIcon(GLYPH[st],'sg'+(st==='cor'?' cor':'')),board.states[st],node('span',col.querySelector('.coln').textContent,'n'));
b.onclick=()=>{phoneCol=st;renderBoard();$('col-tabs').querySelector('.on')?.scrollIntoView({inline:'nearest',block:'nearest'});};
return b;}));
for(const col of cols)col.classList.toggle('pick',col.dataset.state===phoneCol);
}
// Imprimindo, one lane per machine (app/machines.py): its name and places,
// the order printing, the one ripping, then its free place. Every active
// machine has its lane, so a card dragged from the queue can be dropped on
// the machine it goes to print on.
function printingLanes(orders){
const cap=board.printing_cap||2, mine=myMachine()?.id;
const filtered=Object.values(boardFilter).some(Boolean);
const out=[];
const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id));
for(const m of list){
const here=orders.filter(o=>o.machine?.id===m.id)
.sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1));
// Filtered, a lane with nothing to show stays out; unfiltered, the places count every order.
if(filtered&&!here.length)continue;
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id;
const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas');
lane.append(svgIcon(IC.printer,'i s'),node('b',m.name));
// The machine's sheet opens here; an alert due shows a warning dot with its text.
const alerts=m.alerts||[];
if(alerts.length){const mark=node('i',undefined,'lanealert');mark.title=alerts.map(a=>a.text).join(' · ');
mark.setAttribute('aria-hidden','true');lane.append(mark);}
lane.append(node('span',(m.id===mine?'sua máquina · ':'')+load));
lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':'');
lane.tabIndex=0;lane.setAttribute('role','button');lane.setAttribute('aria-label','Ficha da '+m.name);
const openSheet=()=>openMachineSheet(m.id);
lane.onclick=openSheet;
lane.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openSheet();}};
out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;}));
if(!filtered&&n<cap){
const slot=node('div',undefined,'freeslot');slot.dataset.machine=m.id;
slot.append(node('i',undefined,'freemark'),cap-n>1?plural(cap-n,'vaga livre','vagas livres')+' na '+m.name:'Vaga livre na '+m.name);out.push(slot);
}
}
// An order whose machine is gone or off still shows.
const loose=orders.filter(o=>!list.some(m=>m.id===o.machine?.id));
if(loose.length){const lane=node('div',undefined,'lanehead');lane.append(svgIcon(IC.printer,'i s'),node('b','Sem máquina'));out.push(lane,...loose.map(o=>card(o)));}
return out;
}
// The machine lane under the pointer in Imprimindo: the last lane head above it.
function laneAt(column,y){
let found=null;
for(const el of column.querySelectorAll('[data-machine]')){
if(el.getBoundingClientRect().top<=y)found=el.dataset.machine;
}
return found||column.querySelector('.lanehead[data-machine]')?.dataset.machine||null;
}
function markLane(column,id){
for(const l of column.querySelectorAll('.lanehead,.freeslot,.card'))l.classList.toggle('droplane',!!id&&l.dataset.machine===id);
}
// A card's place in the print queue, among the orders of its product (a
// textile machine pulls the next textile order).
const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv'));
// An order waiting for its proof is not in the queue yet (app/proof.py).
const queuePlace=(order,queue)=>queue.filter(o=>uvOrder(o)===uvOrder(order)&&!waitingProof(o)).indexOf(order)+1;
// An operator's test order: no payment, no Tiny.
const isTest=order=>order.payment?.provider==='teste';
const shortAgo=value=>ago(value).replace(/^há /,'');
// What happens next with the order, said on its card, and in what tone:
// act (someone has to do it now), live (printing), rip (ripping), busy (the
// system is working) or wait (nothing to do here).
function nextStep(order,place){
if(order.cancelled_at)return ['Cancelado','wait'];
if(order.state==='cor')return ['Esperando o cliente','wait'];
// The proof card waits for its answer; its order, outside the queue, for that.
if(order.proof_parent&&order.state==='rev')return ['Responder a prova','act'];
if(order.state==='tra'&&waitingProof(order))return ['Aguardando prova','wait'];
if(order.state==='rev')return ['Conferir a folha','act'];
if(order.state==='imp')return partsStep(order)||(order.printing?PRINTING[order.printing].slice(0,2):['Na máquina','wait']);
if(order.state==='tra'){
// The operator whose machine prints this product pulls the first one.
const m=(board.machines||[]).find(x=>x.id===myMachine()?.id);
const fits=!m?.products?.length||order.snapshot.items.some(i=>m.products.includes(i.mode));
if(place===1&&m&&fits&&mayMove('tra','imp'))return ['Puxar da fila','act'];
return [place?place+'º na fila':'Na fila','wait'];
}
const p=printState(order);
if(p.text==='Gerando arquivo…')return ['Gerando o arquivo','busy'];
if(p.text==='Falta aprovar o final')return ['Aprovar o final','act'];
if(p.text==='Correção recebida')return ['Conferir correção','act'];
if(p.text==='Final aprovado')return ['Pronto para a fila','act'];
return [p.text,'act'];
}
// Everything a card has to say beyond its stage, the most urgent first; the
// card shows the first and how many more, and all of them on hover.
function cardFlags(order){
const s=order.snapshot, out=[];
if(order.cancelled_at)return [['bad','Cancelado','Cancelado por '+order.cancelled_by+' em '+when(order.cancelled_at)+': '+order.cancel_reason]];
const live=order.state!=='fin';
// A stalled order says so in red where its time is, not as a mark.
const redo=(order.reworks||[]).filter(r=>r.authorized!==false);
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
if(order.snapshot.treatment){
const n=Number(order.snapshot.treatment.arts)||1;
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
}
if(order.snapshot.redesign){
const n=Number(order.snapshot.redesign.arts)||1;
out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'),
'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']);
}
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']);
// The grade rule set in the Site tab flagged this order for the designer.
if(!order.proof_parent&&s.grade_flags?.aviso!=null)
out.push(['warn','Nota '+s.grade_flags.aviso+': conferir a arte',
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir']);
if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']);
const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0);
if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]);
if(order.treated)out.push(['','Tratada',TREATED_NOTE+' Aprovado por '+order.treated.by+'.']);
if(live&&needsProof(order)&&order.proof_ok_at)out.push(['','Prova OK','Prova conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)]);
if(isTest(order))out.push(['','Teste','Pedido de teste: sem pagamento, não vai ao Tiny']);
return out;
}
function flagNode(flags){
if(!flags.length)return null;
const [tone,text]=flags[0];
const f=node('span',text,'flag tip-l'+(tone?' '+tone:''));f.dataset.tip=flags.map(x=>x[2]).join(' · ');
if(flags.length>1)f.append(node('span',' +'+(flags.length-1),'plus'));
return f;
}
const KIND={file:'Folha',avulsa:'Avulsa',uvfile:'Folha',uv:'Avulsa'};
function productLine(items){
const modes=[...new Set(items.map(i=>i.mode))];
return SHORT[modes[0]]+(items.length>1?' ×'+items.length:'')+(modes.length>1?' +'+(modes.length-1):'');
}
// A card drags forward when this profile makes that move, or up and down
// when it sets the column's order; a card of another operator's machine does not.
function draggable(c,order){
c.draggable=!order.cancelled_at&&!waitingProof(order)&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
c.onclick=()=>openPanel(order.id);
c.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();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'&&mayMove(order.state,s));
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
const moves=forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou '):'';
const priority=mayReorder(order.state)?'arraste para cima ou para baixo para mudar a prioridade':'';
say(moves&&priority?moves+', ou '+priority:moves||priority,false,60000);
};
c.ondragend=()=>{dragging=null;clearDrop();for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');};
}
function card(order,place){
const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at;
const [step,tone]=nextStep(order,place);
const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':''));
c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
const who=buyer(s);
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step);
const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo');
const row=node('span',undefined,'crow');
const late=!!order.late&&!order.cancelled_at;
const age=node('span',shortAgo(order.state_since||order.updated_at),'age'+(late?' late tip-l'+(order.late==='bad'?' late2':''):''));
if(late)age.dataset.tip='Fora do tempo: '+(order.state_hours??'?')+' h nesta etapa · limite '+
(order.limit_hours??'?')+' h · responsável: '+(order.limit_by||'—');
row.append(node('span','#'+order.number,'num'),originTag(order),age);
const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;
const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items)));
const special=specialDelivery(s);
if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);}
if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
meta.append(node('b',metres(orderMetres(order)),'mtr'));
info.append(row,name,meta);
const art=artBox(s.items,'thumb');top.append(art,info);
c.append(top);
if(order.state==='cor'&&order.correction_reason){const r=node('span',undefined,'creason');r.append(node('b','Motivo'),' '+order.correction_reason);c.append(r);}
const foot=node('span',undefined,'cfoot'), next=node('span',undefined,'next'+(tone==='wait'?' wait':''));
if(tone==='live'){const f=node('i',undefined,'feed');f.append(node('i'),node('i'),node('i'));next.append(f);}
if(tone==='rip')next.append(node('i',undefined,'rip'));
if(tone==='busy'){const d=node('i',undefined,'dots');d.append(node('i'),node('i'),node('i'));next.append(d);}
next.append(node('span',step,'stx'));
foot.append(next);
const flag=flagNode(cardFlags(order));if(flag)foot.append(flag);
c.append(foot,cardOpenAction(order));
draggable(c,order);
return c;
}
// Finalizado is the end of the line: what the customer still has to do,
// nothing else. A pickup waiting more than two days is said in warning.
const PICKUP_WARN_DAYS=2;
function miniCard(order){
const c=node('div',undefined,'mini'+(order.id===openOrder?' open':''));c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
const who=buyer(order.snapshot);
const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age'));
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
let text,ic=IC.check,warn=false;
const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000);
const special=specialDelivery(order.snapshot);
if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;}
else if(order.picked_up_at)text='Retirado';
else if(special){text=special;ic=IC.box;}
else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;}
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
else{text='Aguardando retirada';ic=IC.bag;}
const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text);
c.append(row,name,done,cardOpenAction(order));
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text);
draggable(c,order);
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)&&current[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)=>
new Date(a.finished_at||a.updated_at)-new Date(b.finished_at||b.updated_at)||a.id.localeCompare(b.id));
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
if(oldest){params.set('before_finished_at',oldest.finished_at||oldest.updated_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='',machine=null){
await api('/orders/'+order.id+'/move',{state,version:order.version,reason,...(machine?{machine_id:machine}:{})});
await load();
}
// ---- Phone (the design canvas' phone screens) -------------------------------
// Under 700 px the Kanban is the phone mockup: sections at the bottom, menus
// and filters as sheets from the bottom, the order and the quote as pages.
const PHONE=matchMedia('(max-width:700px)');
PHONE.addEventListener('change',()=>{if(board)render();});
// A sheet from the bottom: the grab, then what it holds. Escape or the scrim closes.
function sheet(parts,{label='',role='dialog',onclose}={}){
const scrim=node('div',undefined,'mscrim');
const box=node('div',undefined,'msheet');box.setAttribute('role',role);if(label)box.setAttribute('aria-label',label);
box.append(node('span',undefined,'grab'),...parts);
const entry={box,host:document.body,close(){const i=MODALS.indexOf(entry);if(i<0)return;MODALS.splice(i,1);scrim.remove();box.remove();onclose?.();}};
scrim.onclick=()=>entry.close();
MODALS.push(entry);document.body.append(scrim,box);return entry;
}
// A row of a phone sheet: an icon, the words, and maybe something on the right.
function mrow(d,text,fn,className='mrow',end=null){
const b=node('button',undefined,className);b.type='button';b.setAttribute('role','menuitem');
b.append(svgIcon(d),node('span',text,'mtext'),...(end?[end]:[]));
b.onclick=async()=>{try{await fn();}catch(e){say(e.message,true);}};return b;
}
// "Mais": who is signed in, the sections that do not fit the bar, the machine,
// the theme, the password and Sair.
function phoneMenu(){
let m=null;
const go=fn=>async()=>{m.close();await fn();};
const who=node('div',undefined,'who sheetwho'),words=node('span');
const ava=node('span',initialsOf(ME.name||ME.email),'ava');ava.append(node('i',undefined,'pres on'));
words.append(node('b',ME.name||ME.email),node('span',(ROLE_NAMES[ME.role]||ME.role)+(myMachine()?', na '+myMachine().name:''),'sub'));
who.append(ava,words);
const rows=[];
if(TAB_NEEDS.integrations()){const n=$('badge-integrations').textContent;
rows.push(mrow(IC.link,'Integrações',go(()=>showTab('integrations')),'mrow',n?statePill(n,'warn'):null));}
if(TAB_NEEDS.users())rows.push(mrow(IC.user,'Usuários',go(()=>showTab('users'))));
if(ME.machine_question)rows.push(mrow(IC.printer,'Trocar de máquina',go(()=>askMachine(true)),'mrow',node('span',myMachine()?.name||'','lbl')));
const light=kanbanTheme.get()==='light';
rows.push(mrow(light?ICON_MOON:ICON_SUN,light?'Mudar para o modo escuro':'Mudar para o modo claro',go(()=>{kanbanTheme.toggle();paintThemeToggle();})));
rows.push(mrow(IC.key,'Trocar a senha',go(accountForm)));
rows.push(mrow(IC.logout,'Sair',go(()=>$('logout').click()),'mrow bad'));
const body=node('div',undefined,'sbody');body.append(...rows);
m=sheet([who,body],{label:'Mais',role:'menu'});
}
// The board's filters on the phone: every kind, the product too, and how many
// orders they show.
function phoneFilters(){
const kinds=[{key:'product',label:'Produto',options:PRODUCTS.filter(([v])=>v)},...filterKinds()];
const body=node('div',undefined,'sbody');
const show=node('button','','btn pri');show.type='button';
const paint=()=>{
body.replaceChildren(...kinds.map(kind=>{
const group=node('div',undefined,'fgroup'),opts=node('div',undefined,'fopts');
for(const [value,text] of kind.options){
const on=boardFilter[kind.key]===value;
const b=node('button',text,'fopt'+(on?' on':''));b.type='button';b.setAttribute('aria-pressed',String(on));
b.append(node('span',String(filterCount({...boardFilter,[kind.key]:value})),'n'));
b.onclick=()=>{boardFilter[kind.key]=on?'':value;renderBoard();paint();};opts.append(b);
}
group.append(node('span',kind.label),opts);return group;}));
show.textContent='Ver '+plural(filterCount(boardFilter),'pedido','pedidos');
};
const close=iconButton(IC.close,'Fechar',()=>m.close(),'mic right');
const head=node('div',undefined,'shead');head.append(node('b','Filtros'),close);
const clear=node('button','Limpar','btn');clear.type='button';clear.onclick=()=>{for(const k in boardFilter)boardFilter[k]='';renderBoard();paint();};
const foot=node('div',undefined,'sfoot');foot.append(clear,show);
const m=sheet([head,body,foot],{label:'Filtros'});show.onclick=()=>m.close();
paint();
}
$('more-nav').onclick=()=>phoneMenu();
$('filter-open').onclick=()=>phoneFilters();

1116
web/kanban-order.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -307,4 +307,4 @@
<div class="scrim" id="scrim"></div> <div class="scrim" id="scrim"></div>
<aside class="drawer" id="panel" aria-label="Pedido"></aside> <aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div> </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-quotes.js"></script><script src="/kanban-users.js"></script><script src="/kanban-integrations.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-board.js"></script><script src="/kanban-order.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-integrations.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>

File diff suppressed because it is too large Load Diff

View File

@@ -116,6 +116,8 @@
function apiError(path, status, message, detail) { function apiError(path, status, message, detail) {
if (!started || status === 401 || typeof Sentry === 'undefined') return; if (!started || status === 401 || typeof Sentry === 'undefined') return;
// A restart's few seconds without the database (app/app.py): not a bug.
if (status === 503 && /reiniciando/.test(String(message))) return;
try { try {
// One issue per kind of API error: without this Sentry groups them all // One issue per kind of API error: without this Sentry groups them all
// by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for // by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for