feat: two cards at most in Imprimindo per machine, one printing and one ripping (Dropstar's third round, item 11)
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 4m14s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m5s

A third pull onto the same machine is refused with "máquina5 já tem 2 em
Imprimindo", and so is changing a printing order to a full machine. On
the board, the first order to enter Imprimindo on its machine is labelled
Imprimindo and the next Ripando; the column shows each machine's count,
as "máquina5 · 2/2".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-29 16:19:04 -03:00
parent 757008566c
commit 9c44cdf2a1
5 changed files with 108 additions and 4 deletions

View File

@@ -140,7 +140,7 @@ def board(request: Request, user=Depends(operator)):
'mail': mail.status(c)},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
'machines': machines.rows(c),
'machines': machines.rows(c), '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}
@@ -189,12 +189,15 @@ TREATED = """f.kind='final'
def assign_machines(c, orders):
"""Each order's machine as stored (app/machines.py gives it): chosen by
someone, or automatic. None while no machine prints its product."""
someone, or automatic. None while no machine prints its product. In
Imprimindo, also which of its machine's two places it holds."""
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
slots = machines.printing_slots(c)
for order in orders:
key = str(order.get('machine_id') or '')
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
if key in names else None)
order['printing'] = slots.get(order['id'])
return orders
@@ -634,11 +637,16 @@ def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))):
with db.connect() as c:
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
row = c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s RETURNING number',
(body.machine_id, body.machine_id is not None, uid)).fetchone()
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
machines.route(c)
# Printing already: the machine it goes to must have a place in Imprimindo.
if row['state'] == 'imp' and not row['cancelled_at']:
now = c.execute('SELECT machine_id FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if name := machines.full(c, now['machine_id'], uid):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
return {'ok': True}
@@ -755,6 +763,9 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
# Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
if body.state == 'cor':

View File

@@ -15,6 +15,10 @@ OPEN = ('rec', 'tra', 'imp', 'cor')
MOVABLE = ('rec', 'tra', 'cor')
# One routing at a time, so two at once cannot both pick the same "least loaded".
LOCK = 7_041_901
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
# make the RIP choke; two mean the next sheet is ready when one ends.
PRINTING_CAP = 2
def product_family(order):
@@ -104,3 +108,26 @@ def rows(c, with_operators=False):
row['operators'] = operators.get(key, [])
result.append(row)
return result
def full(c, machine_id, order_id):
"""The machine's name when it already has PRINTING_CAP other orders in
Imprimindo, so this one cannot join them; None when it has room. The
machine's row is locked, so two pulls at once cannot both take the last
place."""
if machine_id is None:
return None
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
return machine['name'] if machine and printing >= PRINTING_CAP else None
def printing_slots(c):
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
machine (ripped, running), 'ripando' for the one after it."""
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
WHERE order_id=o.id AND to_state='imp') m
WHERE o.state='imp' AND o.cancelled_at IS NULL AND o.machine_id IS NOT NULL''').fetchall()}

View File

@@ -311,6 +311,50 @@ def run():
assert (shared['orders'], shared['metres'], shared['printing_hours'], shared['metres_per_hour']) == \
(2, 1.5, 0.5, 3.0), shared
# Two at most in Imprimindo per machine (Dropstar, 2026-10-29): the first
# to come in is printing, the second ripping; a third waits for a place.
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
machines.append(cap)
with db.connect() as c:
pulled = [order_fixture(c, owner, 'file') for _ in range(4)]
made.extend(pulled)
for _, oid in pulled:
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
(upload, owner, f'test/{upload}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(cap, oid))
first, second_in, third, elsewhere = (str(oid) for _, oid in pulled)
pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
'reason': ''}, operator=True)
running = pull(first)
pull(second_in)
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
operator=True, expected=409)
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused
loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
('imprimindo', 'ripando', None)
assert loaded['printing_cap'] == 2
assert next(m for m in loaded['machines'] if m['id'] == cap)['states'] == {'imp': 2, 'tra': 2}
# Nor does an order already printing elsewhere come onto the full machine.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp', machine_id=%s WHERE id=%s", (textil, elsewhere))
su.call(f'/operator/orders/{elsewhere}/machine', {'machine_id': cap}, operator=True, expected=409)
assert next(o for o in su.call('/operator/board', operator=True)['orders']
if o['id'] == elsewhere)['machine']['id'] == textil
# The one printing goes to Revisão: the one ripping is now printing, and a place opens.
su.call(f'/operator/orders/{first}/move', {'state': 'rev', 'version': running['version'], 'reason': ''},
operator=True)
pull(third)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
(None, 'imprimindo', 'ripando')
# Switched off, a machine gives its automatic orders to another one.
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
@@ -386,9 +430,11 @@ def run():
for _, oid in made:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.order_files 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.quotes WHERE id=ANY(%s)', ([q for q, _ in made],))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (owner,))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.machines WHERE id=ANY(%s::uuid[])', (machines,))

View File

@@ -122,6 +122,7 @@ main{padding:0 24px 24px}
.col-head small{font-size:13.5px;color:var(--faint)}
.col-head .col-sub{justify-content:space-between;min-height:30px}
.col-head .col-sub small{white-space:nowrap}
.col-head .col-slots{flex-wrap:wrap;gap:5px}
.col .empty{font-size:13.5px;color:var(--faint);padding:8px 2px}
.card{text-align:left;display:flex;flex-direction:column;gap:8px;padding:12px;border-radius:10px;border:1px solid var(--line2);background:var(--card);width:100%}
.card:hover,.card.open{border-color:var(--line3);background:#1E2226}

View File

@@ -593,6 +593,23 @@ const TREATED_NOTE='O arquivo final foi preparado pela equipe, não é a arte qu
// 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';
// 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','ok','Já ripou, está rodando'],
ripando:['Ripando','info','O Flexi está ripando enquanto o anterior roda']};
// "máquina5 · 2/2" for each machine that prints, or has an order printing.
// An operator who works on some machines sees those.
function printingRoom(){
const cap=board.printing_cap, mine=ME?.role==='operador'&&ME.machines?.length?ME.machines:null;
const list=(board.machines||[]).filter(m=>(m.active||m.states.imp)&&(!mine||mine.includes(m.id)));
if(!list.length)return null;
const room=node('div',undefined,'col-slots');
room.append(...list.map(m=>{const n=m.states.imp||0;
const chip=node('span',m.name+' · '+n+'/'+cap,'pill '+(n>cap?'bad':n===cap?'warn':'muted'));
chip.title=n>=cap?m.name+' está cheia: abre vaga quando um pedido sair de Imprimindo':m.name+' tem '+(cap-n)+' vaga'+(cap-n===1?'':'s');
return chip;}));
return room;
}
async function proofOk(order){
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
}
@@ -712,6 +729,7 @@ function renderBoard(){
sub.append(tools);
}
head.append(line,sub);
if(state==='imp'){const room=printingRoom();if(room)head.append(room);}
column.append(head);
for(const order of orders)column.append(card(order));
if(state==='fin'&&finishedMore&&!Object.values(boardFilter).some(Boolean))moreButton(column,true,loadOlderFinished);
@@ -750,6 +768,7 @@ function card(order){
else if(order.state!=='fin'){
const p=printState(order);
flags.append(badge((p.tone==='ok'?'✓ ':p.tone==='warn'?'! ':'')+p.text,p.tone));
if(order.printing)flags.append(badge(...PRINTING[order.printing]));
if(s.items.some(i=>i.quality_status==='warning'))flags.append(badge('! Ressalva','warn','O cliente aceitou a ressalva de resolução'));
if(s.items.some(mirroredItem))flags.append(badge('Espelhado','bad',MIRROR_NOTE));
if(stalled(order))flags.append(badge('⏱ Parado '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));