feat: the proof card, machine pull and print file corrections (Dropstar, 05/11)

The proof card owns its final PNG, keeps its parent locked until the seller
answers, enters the queue first, and shares one machine with the parent.
The board no longer assigns a machine at payment; the puller records it.
A stalled print file times out with a card warning and a retry, finished
orders sort by completion, and finals are stored as PNG. The original
download carries the order number (items 0.1, 0.4 to 0.7 and 0.9).
This commit is contained in:
Cauê Faleiros
2026-11-06 10:41:20 -03:00
parent 0fc01315c7
commit d69e326125
20 changed files with 584 additions and 220 deletions

View File

@@ -8,6 +8,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from ..core import db
from .. import proof
from ..artwork import submit_files
from ..core.auth import can, operator
from ..core.models import ArtworkSubmission, UploadStart
@@ -18,9 +19,14 @@ router = APIRouter()
@router.post('/api/operator/orders/{oid}/uploads')
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found')
if row['parent_id']:
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
proof.require_unlocked(c, row)
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
return begin_upload(body, session_id=operator_identity(user))
@@ -52,4 +58,7 @@ def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
if not order: raise HTTPException(404, 'Order not found')
if order['parent_id']:
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
proof.require_unlocked(c, order)
return submit_files(c,order,body,operator_identity(user),'final',user)

View File

@@ -17,7 +17,7 @@ from ..core import db
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import file_prefix, queue as queue_print_files
from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files
from .. import cnpj, hotfolder, machines, mail, payments, proof, quote_review, receipt
from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
@@ -105,15 +105,16 @@ def backup_now(user=Depends(can('integrations'))):
@router.get('/api/operator/board')
def board(user=Depends(operator)):
with db.connect() as c:
# Orders that arrived, or lost their machine, get one before the board is read.
machines.route(c)
# 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.
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
# A proof card that got its answer is done with (app/proof.py).
finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall()
finished = c.execute('''SELECT * FROM (
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
) f ORDER BY finished_at DESC,id DESC LIMIT %s''', (BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
@@ -129,7 +130,7 @@ def board(user=Depends(operator)):
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
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 + list(reversed(finished)))
orders = with_print_files(c, active + finished)
# 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.
@@ -192,16 +193,20 @@ 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. In
Imprimindo, also which of its machine's two places it holds."""
"""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()}
slots = machines.printing_slots(c)
ids = [o['id'] for o in orders] + [o['proof_card']['id'] for o in orders if o.get('proof_card')]
pulled = {r['order_id']: r for r in c.execute('''SELECT DISTINCT ON (order_id) order_id,operator,created_at
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='imp' AND NOT back
ORDER BY order_id,id DESC''', (ids,)).fetchall()}
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'])
by = pulled.get(order['id']) or (pulled.get(order['proof_card']['id']) if order.get('proof_card') else None)
order['machine_pulled'] = {'by': by['operator'], 'at': by['created_at']} if by else None
return orders
@@ -209,9 +214,11 @@ def with_print_files(c, orders):
"""Each order with its generated print files, the items whose final file is
approved, and the customer's corrections waiting to be approved as finals."""
ids = [o['id'] for o in orders]
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at,
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out,
p.claimed_at+%s AS timeout_at,u.name
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall()
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
# A film over 15 m is several PNGs, in order (item 13).
parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
@@ -278,15 +285,18 @@ def cursor_pair(first, second):
@router.get('/api/operator/orders/finished')
def finished_page(before_created_at: datetime | None = None, before_id: UUID | None = None,
def finished_page(before_finished_at: datetime | None = None, before_id: UUID | None = None,
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
"""Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_created_at, before_id)
paged = cursor_pair(before_finished_at, before_id)
with db.connect() as c:
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
rows = c.execute('''SELECT * FROM (
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
) f ''' + ('WHERE (finished_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY finished_at DESC,id DESC LIMIT %s''',
((before_finished_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
orders = with_print_files(c, rows[:limit])
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
'names': company_names(c, orders)}
@@ -681,23 +691,34 @@ class MachineChoice(StrictModel):
@router.post('/api/operator/orders/{uid}/machine')
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
"""Send an order to a machine, or back to the automatic choice (None).
Not the operator: their pull makes an order their machine's (item 12)."""
"""Exceptional manual choice before printing; the operator's pull is final."""
if request.state.operator['role'] == 'operador':
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
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.')
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not current:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, current)
if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'):
raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.')
if body.machine_id:
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
if machines.product_family(current) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders
WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']:
raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.')
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.')
if current['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, current['parent_id']))
elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'):
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, linked['id']))
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
return {'ok': True}
@@ -708,10 +729,11 @@ def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce')
measure comes prefilled, and whoever prepares the art may change it until
the order prints. Both stay: the measure in the snapshot, the choice here."""
with db.connect() as c:
row = c.execute('SELECT snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, row)
if body.item_index >= len(row['snapshot']['items']):
raise HTTPException(422, 'Item não encontrado no pedido.')
# Printing, the class still changes while the item's files wait to go
@@ -799,6 +821,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
# Back to Arte recebida with the reason; its final is approved again.
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],))
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
machine_id=NULL,machine_chosen=false,
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
@@ -819,7 +842,6 @@ def new_proof_card(uid: UUID, user=Depends(can('produce'))):
child = proof.create_child(c, row)
if not child:
raise HTTPException(409, 'Este pedido não leva prova.')
machines.route(c)
audit('order_proof_card', order=row['number'], operator=user)
return {'ok': True, 'id': child['id'], 'number': child['number']}
@@ -956,9 +978,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
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, machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
row = c.execute('SELECT id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if not may_reorder(request.state.operator['role'], row['state']):
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
mine = request.state.operator['machine']
@@ -996,6 +1019,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
if row.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
proof.require_unlocked(c, row)
if body.state == row['state']:
return row
back = BACK.get(row['state']) == body.state
@@ -1008,9 +1032,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(422, 'Informe o motivo da correção.')
if back and not body.reason.strip():
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
# The machine of this session (item 12): pulling a card from the queue
# makes it that machine's ("a máquina real do card é a que puxou"); an
# operator pulls any card but moves only their machine's.
# The machine of this session takes a card when it is pulled. A proof
# and its parent must keep the same physical machine.
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
@@ -1019,29 +1042,26 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
# Dropped on a machine's lane in Imprimindo: that machine, when it
# prints the product. The operator's pull stays their machine's.
if pulling and body.machine_id:
if account['role'] == 'operador':
if str(body.machine_id) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
else:
target = c.execute('SELECT name, products, active FROM dtf_local.machines WHERE id=%s',
(body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
row['machine_id'] = body.machine_id
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', (body.machine_id, uid))
if pulling and session_machine and not body.machine_id and (account['role'] == 'operador' or not row['machine_chosen']):
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
if machines.product_family(row) in (prints or {}).get('products', []):
row['machine_id'] = session_machine['id']
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
(session_machine['id'], uid))
elif account['role'] == 'operador':
raise HTTPException(409, f"A {session_machine['name']} não imprime este produto.")
if pulling:
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
if not chosen:
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
if not target or not target['active']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['machine_id'] and chosen != linked['machine_id']:
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
row['machine_id'] = chosen
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
if row['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
(chosen, row['parent_id']))
# Arte conferida is the queue: what enters it has its final files approved.
if body.state in ('tra','imp'):
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
@@ -1077,9 +1097,10 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
hotfolder.start(c, uid)
# A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL,
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(),
queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END,
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
WHERE id=%s RETURNING *''', (body.state, due, uid)).fetchone()
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
@@ -1104,9 +1125,10 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
"""Queue generation again for items that failed or went to manual preparation,
and for orders paid before the generator existed."""
with db.connect() as c:
row = c.execute('SELECT id,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if row['state'] not in ('rec','tra'):
raise HTTPException(409, 'Print files are generated only before the order is queued')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
@@ -1634,7 +1656,7 @@ def queue_folder(body: FolderSync, user=Depends(can('print'))):
@router.get('/api/operator/uploads/{uid}/download')
def download(uid: UUID, user=Depends(operator)):
def download(uid: UUID, order_id: UUID | None = None, user=Depends(operator)):
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
if not row:
@@ -1642,4 +1664,15 @@ def download(uid: UUID, user=Depends(operator)):
if row['expires_at'] <= datetime.now(timezone.utc):
raise HTTPException(410, 'Artwork retention expired')
require_clean(row)
return {'name':row['name'], 'url':storage.download(row['object_key'],row['name']), 'expires_in':300}
name = row['name']
if order_id:
order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']]
if str(uid) not in originals:
raise HTTPException(422, 'Este arquivo não é original do pedido.')
index = originals.index(str(uid)) + 1
suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin'
name = f'DTF-{order["number"]}-original-{index}.{suffix}'
return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300}

View File

@@ -231,7 +231,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
machines.route(c)
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -248,20 +247,21 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
raise HTTPException(404, 'Máquina não encontrada.')
if not body.active:
release_sessions(c, mid)
machines.route(c)
audit('machine_updated', operator=user, machine=body.name)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/delete')
def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders go back to the automatic choice; its operators lose it."""
"""Its orders lose that machine; its operators lose the session choice."""
with db.connect() as c:
if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1",
(mid,)).fetchone():
raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.')
release_sessions(c, mid)
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
machines.route(c)
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}