feat: Kanban columns are queues, and a card can be dragged up or down
Some checks failed
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Failing after 3m24s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
Some checks failed
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Failing after 3m24s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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__':
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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 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'});
|
||||
|
||||
Reference in New Issue
Block a user