From 894e75fd94f543577f3384d91eec2d1d5d01a1c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 2 Oct 2026 16:57:31 -0300 Subject: [PATCH] feat: Kanban columns are queues, and a card can be dragged up or down Each column is sorted explicitly by payment time, first paid on top, however the board's list was put together (older finished orders, one opened from the search). A card dragged within its column lands between the two it was dropped between (queue_key, halfway between their keys) and keeps that place for everyone; moving to another stage clears it. Reordering is not activity: the stalled clock keeps running. Co-Authored-By: Claude Opus 5.5 --- app/api/operator.py | 44 ++++++++++++++++++++++++++++++-- app/schema.sql | 4 +++ tests/order_actions_test.py | 23 ++++++++++++++--- web/kanban.css | 4 +++ web/kanban.js | 51 ++++++++++++++++++++++++++++++++----- 5 files changed, 114 insertions(+), 12 deletions(-) diff --git a/app/api/operator.py b/app/api/operator.py index 1a7a06e..bbc6972 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -13,7 +13,7 @@ from fastapi.responses import RedirectResponse from ..core import db from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, operator, login_failed, password_matches, throttle) -from ..core.models import Move, OperatorLogin, Resolution, Review +from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..printjobs import queue as queue_print_files from .. import payments, quote_review from .. import tiny @@ -402,6 +402,46 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(operator)): return {'ok': True} +class QueuePlace(StrictModel): + """Where a dragged card lands: between two orders of its column, either + of them absent at the top or the bottom.""" + after: UUID | None = None + before: UUID | None = None + + +QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))' + + +@router.post('/api/operator/orders/{uid}/queue') +def queue_place(uid: UUID, body: QueuePlace, user=Depends(operator)): + """An order's place in its column: by default its payment time; dragged, + halfway between the orders it was dropped between. It neither changes the + order's stage nor counts as activity (the stalled clock keeps running).""" + if not body.after and not body.before: + raise HTTPException(422, 'Informe entre quais pedidos ele fica.') + with db.connect() as c: + row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Order not found') + keys = {} + for side in ('after', 'before'): + other = getattr(body, side) + if other: + near = c.execute(f'SELECT state, {QUEUE_KEY} AS key FROM dtf_local.orders WHERE id=%s', (other,)).fetchone() + if not near or near['state'] != row['state']: + raise HTTPException(409, 'Os pedidos mudaram de etapa. Clique em Atualizar.') + keys[side] = float(near['key']) + if 'after' in keys and 'before' in keys: + key = (keys['after'] + keys['before']) / 2 + elif 'after' in keys: + key = keys['after'] + 60 + else: + key = keys['before'] - 60 + c.execute('UPDATE dtf_local.orders SET queue_key=%s WHERE id=%s', (key, uid)) + audit('order_queue_moved', order=str(uid), operator=user) + return {'ok': True, 'queue_key': key} + + @router.post('/api/operator/orders/{uid}/move') def move(uid: UUID, body: Move, user=Depends(operator)): with db.connect() as c: @@ -429,7 +469,7 @@ def move(uid: UUID, body: Move, user=Depends(operator)): c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,)) c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)', (uid,row['state'],body.state,user,body.reason,back)) - changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now() WHERE id=%s RETURNING *', (body.state,uid)).fetchone() + changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone() events = {'imp':'production_started','cor':'correction_needed','fin':'ready'} if body.state in events and not back and not payments.is_test(row): # "Production started" and "ready" reach the customer once per order, diff --git a/app/schema.sql b/app/schema.sql index 1e52123..687c513 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -222,3 +222,7 @@ ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_by text; ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_at timestamptz; ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_by text; ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text; + +-- An order's place in its column's queue, when an operator dragged it up or +-- down. Empty means "by payment time"; it is cleared when the order moves on. +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision; diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 4f4dbed..2285add 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -18,10 +18,11 @@ def run(): mail = f'actions-{uuid4().hex[:8]}@example.test' approved = {'customer': {'mail': mail}, 'items': [], 'total_cents': 1490} discard, test_quote, paid_quote, paid_order = uuid4(), uuid4(), uuid4(), uuid4() + newer_quote, newer_order = uuid4(), uuid4() test_order = None try: with db.connect() as c: - for qid in (discard, test_quote, paid_quote): + for qid in (discard, test_quote, paid_quote, newer_quote): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved))) @@ -63,6 +64,20 @@ def run(): operator=True, expected=409) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404) + # Dragged within its column: first paid first, unless moved; moving on resets it. + with db.connect() as c: + c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,)) + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at) + VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved), + Jsonb({'provider': 'teste', 'id': 't'}))) + client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True) + with db.connect() as c: + keys = {str(r['id']): r['k'] for r in c.execute( + 'SELECT id, COALESCE(queue_key, extract(epoch FROM created_at)) AS k FROM dtf_local.orders WHERE id=ANY(%s)', + ([paid_order, newer_order],)).fetchall()} + assert keys[str(newer_order)] < keys[str(paid_order)], keys + client.call(f'/operator/orders/{newer_order}/queue', {}, operator=True, expected=422) + # Cancelled, it can be deleted; its quote is discarded, not unpaid again. client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True) with db.connect() as c: @@ -72,13 +87,13 @@ def run(): print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete') finally: with db.connect() as c: - for oid in filter(None, (test_order, paid_order)): + for oid in filter(None, (test_order, paid_order, newer_order)): for table in ('movements', 'order_files', 'print_files'): c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (oid,)) c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,)) - c.execute('DELETE FROM dtf_local.orders WHERE quote_id=ANY(%s)', ([discard, test_quote, paid_quote],)) - c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([discard, test_quote, paid_quote],)) + c.execute('DELETE FROM dtf_local.orders WHERE quote_id=ANY(%s)', ([discard, test_quote, paid_quote, newer_quote],)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([discard, test_quote, paid_quote, newer_quote],)) if __name__ == '__main__': diff --git a/web/kanban.css b/web/kanban.css index 17c4f15..e16d369 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -356,3 +356,7 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom} /* The order code the customer sees, beside the operators' number. */ .ocode{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)} + +/* Where a card dragged within its column will land. */ +.card.drop-before{box-shadow:0 -3px 0 0 var(--accent)} +.card.drop-after{box-shadow:0 3px 0 0 var(--accent)} diff --git a/web/kanban.js b/web/kanban.js index e4c63e2..d8f9f7c 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -300,7 +300,9 @@ function renderBoard(){ $('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]); - const orders=board.orders.filter(o=>o.state===state&&matches(o)); + // 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]); @@ -313,11 +315,18 @@ function renderBoard(){ 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(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');}; - column.ondragleave=()=>column.classList.remove('target'); + 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&&order.state!==state)try{await move(order,state);}catch(error){say(error.message,true);}}; + 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; })); } @@ -345,14 +354,44 @@ function card(order){ 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 '):'Pedido finalizado',false,60000); + 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=()=>{for(const col of document.querySelectorAll('.col'))col.classList.remove('allowed','target');say('');}; + 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 yc.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