diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 775261c..edac103 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test mail_test thumbnail_backfill_test launch_reset_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/operator.py b/app/api/operator.py index 5cb7aac..69f8390 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -105,6 +105,8 @@ def backup_now(user=Depends(can('integrations'))): @router.get('/api/operator/board') def board(user=Depends(operator)): with db.connect() as c: + limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} + for row in c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()} # Everything still in progress, however old: an operator must never lose a # card they can act on. Finished orders are terminal and only accumulate, # so the board carries a recent window of them and reports the true total. @@ -131,6 +133,7 @@ def board(user=Depends(operator)): LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n'] orders = with_print_files(c, active + finished) + assign_late(c, orders, limits) # A paid notification that did not become an order is money received # for nothing the factory will make. The board carries the count; the # Pagamentos tab pages through them until someone records a resolution. @@ -148,7 +151,45 @@ def board(user=Depends(operator)): 'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), 'names': company_names(c, orders, quotes), - 'pending_total': pending_total, 'approved_total': approved_total} + 'pending_total': pending_total, 'approved_total': approved_total, + 'stage_limits': limits} + + +class StageLimit(StrictModel): + state: Literal['rec', 'tra', 'imp', 'rev', 'fin'] + hours: Decimal = Field(gt=0, le=10000) + responsible: str = Field(default='', max_length=80) + + +class StageLimits(StrictModel): + limits: list[StageLimit] = Field(min_length=1, max_length=5) + + +@router.get('/api/operator/stage-limits') +def get_stage_limits(user=Depends(operator)): + with db.connect() as c: + rows = c.execute('''SELECT state,hours,responsible,updated_by,updated_at + FROM dtf_local.stage_limits ORDER BY array_position(ARRAY['rec','tra','imp','rev','fin'],state)''').fetchall() + return {'limits': [{'state': row['state'], 'hours': float(row['hours']), + 'responsible': row['responsible'], 'updated_by': row['updated_by'], + 'updated_at': row['updated_at']} for row in rows]} + + +@router.post('/api/operator/stage-limits') +def set_stage_limits(body: StageLimits, user=Depends(can('manage'))): + seen = set() + with db.connect() as c: + for limit in body.limits: + if limit.state in seen: + raise HTTPException(422, 'Cada etapa aparece uma vez.') + seen.add(limit.state) + c.execute('''INSERT INTO dtf_local.stage_limits(state,hours,responsible,updated_by,updated_at) + VALUES(%s,%s,%s,%s,now()) + ON CONFLICT (state) DO UPDATE SET hours=EXCLUDED.hours,responsible=EXCLUDED.responsible, + updated_by=EXCLUDED.updated_by,updated_at=now()''', + (limit.state, limit.hours, limit.responsible.strip(), user)) + audit('stage_limits_changed', operator=user, states=','.join(sorted(seen))) + return {'ok': True} def uploads_of(rows): @@ -192,6 +233,35 @@ TREATED = """f.kind='final' AND k.kind='correction')""" +def assign_late(c, orders, limits): + """How long each card has been in its stage, and whether it passed the + limit Gestão set (front 11). A finished card with pickup is not late.""" + ids = [order['id'] for order in orders] + if not ids: + return + entered = {} + for row in c.execute('''SELECT order_id,to_state,created_at FROM dtf_local.movements + WHERE order_id=ANY(%s) AND NOT back ORDER BY created_at''', (ids,)).fetchall(): + entered[(str(row['order_id']), row['to_state'])] = row['created_at'] + now = datetime.now(timezone.utc) + for order in orders: + if order.get('cancelled_at'): + continue + limit = limits.get(order['state']) + if not limit or (order['state'] == 'fin' and order.get('picked_up_at')): + continue + since = entered.get((str(order['id']), order['state'])) + if not since and order['state'] == 'fin': + since = order.get('finished_at') + since = since or order['created_at'] + hours = max(0.0, (now - since).total_seconds() / 3600) + limit_hours = float(limit['hours']) + order['state_hours'] = round(hours, 2) + order['limit_hours'] = limit_hours + order['limit_by'] = limit['responsible'] + order['late'] = 'bad' if hours >= limit_hours * 2 else 'warn' if hours >= limit_hours else None + + def assign_machines(c, orders): """Each machine, its pull attribution, and its printing place.""" names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()} @@ -1310,6 +1380,9 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start within = f"{LOCAL_DAY} BETWEEN %s AND %s" metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)" with db.connect() as c: + limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall() + limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} + for row in limit_rows} total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id @@ -1344,6 +1417,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start (SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state), o.created_at))) / 3600 AS oldest_hours FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall() + # Passages past each stage's acceptable time (front 11), in the + # selected period and today. + late_rows = c.execute(f'''SELECT state, + extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')} AS seconds, + (until AT TIME ZONE 'America/Sao_Paulo')::date AS day + FROM ({spans}) s WHERE until IS NOT NULL''', period + period).fetchall() printed = machine_output(c, start, end) # Rework of the period (D-02 to D-04): the authorized ones, by the day # they were opened, over the film the machines printed in it. @@ -1423,6 +1502,14 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s, percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n FROM samples WHERE seconds >= 0''', period).fetchone() + today = datetime.now(timezone(timedelta(hours=-3))).date() + late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')} + for row in late_rows: + limit = limits.get(row['state']) + if limit and row['seconds'] > limit['hours'] * 3600: + late[row['state']]['count'] += 1 + if row['day'] == today: + late[row['state']]['today'] += 1 series = [] for offset in range((end - start).days + 1): day = start + timedelta(days=offset) @@ -1441,6 +1528,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start 'median_hours': hours(origins[name]['median_hours']) if name in origins else None} for name in ORIGINS], 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, + 'stage_limits': limits, 'late': late, 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], 'median_hours': hours(row['median_hours'])} for row in stages}, 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, diff --git a/app/schema.sql b/app/schema.sql index 6a4296f..340a6da 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -315,6 +315,21 @@ DO $$ BEGIN INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1'); END IF; END $$; +-- Acceptable time per stage (front 11): Gestão edits these; a card past the +-- limit turns yellow, at twice the limit red. `responsible` is who the board +-- names for that column. The final stage counts days without pickup. +CREATE TABLE IF NOT EXISTS dtf_local.stage_limits ( + state text PRIMARY KEY CHECK (state IN ('rec','tra','imp','rev','fin')), + hours numeric NOT NULL CHECK (hours > 0), + responsible text NOT NULL DEFAULT '', + updated_by text NOT NULL DEFAULT 'sistema', + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES + ('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'), + ('rev',2,'Revisor'), ('fin',72,'Atendimento') +ON CONFLICT (state) DO NOTHING; + -- The machines an operator works on; none means every machine. CREATE TABLE IF NOT EXISTS dtf_local.operator_machines ( operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE, diff --git a/tests/stage_limits_test.py b/tests/stage_limits_test.py new file mode 100644 index 0000000..99a5b6d --- /dev/null +++ b/tests/stage_limits_test.py @@ -0,0 +1,46 @@ +"""Acceptable time per stage: Gestão edits it, the board marks the late cards.""" +from uuid import uuid4 + +from psycopg.types.json import Jsonb + +from app.core import db +from tests.smoke_test import Client +from tests.users_test import order_fixture + + +def run(): + client = Client() + client.call('/session') + defaults = [{'state': 'rec', 'hours': 2, 'responsible': 'Designer'}, + {'state': 'tra', 'hours': 6, 'responsible': 'Operador'}, + {'state': 'imp', 'hours': 4, 'responsible': 'Operador'}, + {'state': 'rev', 'hours': 2, 'responsible': 'Revisor'}, + {'state': 'fin', 'hours': 72, 'responsible': 'Atendimento'}] + seen = client.call('/operator/stage-limits', operator=True)['limits'] + assert {row['state'] for row in seen} == {'rec', 'tra', 'imp', 'rev', 'fin'}, seen + client.call('/operator/stage-limits', {'limits': defaults}, operator=True) + owner = uuid4() + with db.connect() as c: + quote, order = order_fixture(c, owner, 'file') + c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '3 hours' WHERE id=%s", (order,)) + try: + board = client.call('/operator/board', operator=True) + mine = next(o for o in board['orders'] if o['id'] == str(order)) + assert mine['late'] == 'warn' and mine['limit_hours'] == 2, mine + assert board['stage_limits']['rec'] == {'hours': 2.0, 'responsible': 'Designer'}, board['stage_limits'] + faster = [row for row in defaults if row['state'] != 'rec'] + [ + {'state': 'rec', 'hours': 1, 'responsible': 'Designer'}] + client.call('/operator/stage-limits', {'limits': faster}, operator=True) + board = client.call('/operator/board', operator=True) + mine = next(o for o in board['orders'] if o['id'] == str(order)) + assert mine['late'] == 'bad' and mine['limit_hours'] == 1, mine + print('PASS: stage limits are editable and a card past the limit is yellow/red') + finally: + client.call('/operator/stage-limits', {'limits': defaults}, operator=True) + with db.connect() as c: + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,)) + + +if __name__ == '__main__': + run() diff --git a/web/kanban.css b/web/kanban.css index b176c3c..c9e1b4b 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -234,6 +234,14 @@ main{padding:0} .col{display:flex;flex-direction:column;gap:8px;min-width:0;min-height:240px;background:var(--lane);border-radius:14px;padding:8px;transition:background .15s,box-shadow .15s} .col.allowed{box-shadow:inset 0 0 0 1.5px color-mix(in srgb,var(--acc) 40%,transparent)} .col.target{box-shadow:inset 0 0 0 2px var(--acc);background:color-mix(in srgb,var(--acc) 5%,var(--lane))} +.latebar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:0 0 10px;padding:9px 12px;border:1px solid var(--ln2);border-radius:9px;background:var(--sf);font-size:12px} +.latebar[hidden]{display:none} +.latebar>b{color:var(--bad);font-family:inherit;font-size:12px} +.latechip{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--ln2);border-radius:7px;background:var(--sf3);color:var(--tx);padding:4px 7px;font:inherit;font-size:11px;cursor:pointer} +.latechip:hover{border-color:var(--bad)} +.latechip i{width:7px;height:7px;border-radius:999px;background:var(--warn)} +.latechip.bad i{background:var(--bad)} +.latebar .btn{margin-left:auto;min-height:28px;font-size:11px} .colhead{display:flex;align-items:center;gap:10px;padding:8px 8px 6px} .coltx{display:flex;flex-direction:column;gap:1px;min-width:0;flex:1} .colhead h2{margin:0;font-size:14px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} diff --git a/web/kanban.html b/web/kanban.html index 85e707f..786484a 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -98,6 +98,7 @@
+

Tempo em cada etapa

-
EtapaMedianaAgora
+
EtapaMedianaAceitávelEstourosAgora

Velocidade do site e do Prumo

EtapaMédiap95Amostras
diff --git a/web/kanban.js b/web/kanban.js index e434bdc..b3eccc6 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -16,7 +16,6 @@ const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.p ', '+(item.stroke_class==='C3'?'chapado':'traço fino'):''); 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',cancelled:'Pedido cancelado'}; -const LATE_HOURS=4; // Payment outcomes are recorded by the API in English; operators read Portuguese. function outcomeText(outcome){ const rules=[ @@ -677,7 +676,7 @@ function printState(order){ 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','imp','rev'].includes(order.state)&&Date.now()-new Date(order.updated_at)>LATE_HOURS*3600000; +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'; @@ -742,6 +741,7 @@ const FILTER_TESTS={ 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=> @@ -761,7 +761,7 @@ 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:[['parados','Parados há mais de '+LATE_HOURS+' h','Parados'], + {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); @@ -842,7 +842,27 @@ const GLYPH={ 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'); + const late=board.orders.filter(o=>!o.cancelled_at&&o.late) + .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; @@ -1049,9 +1069,10 @@ function card(order,place){ 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=stalled(order)&&!order.cancelled_at; - const age=node('span',shortAgo(order.updated_at),'age'+(late?' late tip-l':'')); - if(late)age.dataset.tip='Parado: sem mudar de etapa desde '+when(order.updated_at); + 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))); @@ -1194,6 +1215,31 @@ function formDialog(title,{text,fields=[],label='Salvar',tone='pri',host,width,n } // The old name, for the dialogs of Usuários and the rework. function dialog(title,fields,onsave){return formDialog(title,{fields,onsave:async()=>{await onsave();}});} +// Front 11: Gestão edits the acceptable time and the person responsible for +// each column. The cards read the same table on the next board refresh. +const STAGE_LABELS={rec:'Arte recebida',tra:'Arte conferida',imp:'Imprimindo',rev:'Revisão',fin:'Finalizado sem retirada'}; +function stageLimitsDialog(){ + api('/stage-limits').then(({limits})=>{ + const current=Object.fromEntries((limits||[]).map(limit=>[limit.state,limit])); + const inputs={},fields=[]; + for(const state of ['rec','tra','imp','rev','fin']){ + const limit=current[state]||{hours:2,responsible:''}; + const hours=node('input');hours.type='number';hours.min='0.1';hours.step='0.5';hours.value=limit.hours; + const who=node('input');who.value=limit.responsible||'';who.maxLength=80; + inputs[state]={hours,who}; + fields.push(field(STAGE_LABELS[state]+' (horas)',hours,state==='fin'?'Use 72 para 3 dias.':'')); + fields.push(field('Responsável por '+STAGE_LABELS[state].toLowerCase(),who)); + } + formDialog('Tempos aceitáveis por etapa',{host:$('drawer'),width:640,fields, + note:'Amarelo ao passar do limite; vermelho no dobro.', + onsave:async()=>{ + const limits=Object.entries(inputs).map(([state,{hours,who}])=>({ + state,hours:Number(hours.value),responsible:who.value.trim()})); + await api('/stage-limits',{limits}); + say('Tempos aceitáveis atualizados.');await load(); + }}); + }).catch(error=>say(error.message,true)); +} function field(label,input,hint){ const l=node('label',undefined,'fld');l.append(label,input);if(hint)l.append(node('small',hint));return l; } @@ -2565,10 +2611,13 @@ async function loadStats(){ const tr=node('tr'),name=node('td'),line=node('span',undefined,'stagecell'); line.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')),board.states[state]);name.append(line); const st=data.stages[state], now=data.waiting[state]; + const limit=data.stage_limits?.[state], late=data.late?.[state]||{count:0,today:0}; // Orders; when some came back to the stage, how many times it was entered. const passed=st?plural(st.orders,'pedido','pedidos')+(st.passages>st.orders?', '+st.passages+' passagens':''):'nenhum'; name.append(node('span',passed,'sub')); tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'), + node('td',limit?duration(limit.hours):'—','r'), + node('td',late.count?String(late.count)+(late.today?' · '+late.today+' hoje':''):'—','r'), node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted')); return tr;})); // Speed (item 0.12): average and p95 of what the customer feels.