feat: the machine is chosen at sign-in, per session (Dropstar's third round, item 12)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
After signing in, the Kanban asks "Em qual máquina você está?": required
for the operator, optional for Gestão and Administrador ("Não estou em
máquina"), never for the other profiles. The session keeps it until it
ends or is changed from the header, where the machine shows in green;
one person on two computers runs two machines. Someone else already on
the machine is a warning, not a refusal.
Operators see the whole board (no more per-machine filter). From Arte
conferida they pull any card, which becomes their machine's (a machine
that does not print its product refuses it); they move only their
machine's cards, and the others show without drag or buttons. Their
cards and their machine's row in Imprimindo are outlined in green. The
history records the machine with the person: "Imprimindo · Thales ·
máquina2". Usuários shows who is on each machine now, read-only; the old
operator/machine assignment is no longer read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -102,7 +102,7 @@ def backup_now(user=Depends(can('integrations'))):
|
||||
|
||||
|
||||
@router.get('/api/operator/board')
|
||||
def board(request: Request, user=Depends(operator)):
|
||||
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)
|
||||
@@ -127,7 +127,7 @@ def board(request: Request, 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 = visible(request, with_print_files(c, active + list(reversed(finished))))
|
||||
orders = with_print_files(c, active + list(reversed(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.
|
||||
@@ -202,15 +202,6 @@ def assign_machines(c, orders):
|
||||
return orders
|
||||
|
||||
|
||||
def visible(request, orders):
|
||||
"""An operator who works on some machines sees only their orders."""
|
||||
account = request.state.operator
|
||||
if account['role'] != 'operador' or not account['machines']:
|
||||
return orders
|
||||
mine = set(account['machines'])
|
||||
return [o for o in orders if o.get('machine') and o['machine']['id'] in mine]
|
||||
|
||||
|
||||
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."""
|
||||
@@ -264,7 +255,7 @@ def cursor_pair(first, second):
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/finished')
|
||||
def finished_page(request: Request, before_created_at: datetime | None = None, before_id: UUID | None = None,
|
||||
def finished_page(before_created_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)
|
||||
@@ -273,7 +264,7 @@ def finished_page(request: Request, before_created_at: datetime | None = None, b
|
||||
''' + ('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()
|
||||
orders = visible(request, with_print_files(c, rows[:limit]))
|
||||
orders = with_print_files(c, rows[:limit])
|
||||
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
||||
'names': company_names(c, orders)}
|
||||
|
||||
@@ -393,7 +384,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
|
||||
|
||||
|
||||
@router.get('/api/operator/search')
|
||||
def search(request: Request, q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
||||
def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
||||
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
|
||||
CNPJ or WhatsApp, the delivery recipient, or the order number."""
|
||||
match, params = customer_match('snapshot', q)
|
||||
@@ -416,7 +407,7 @@ def search(request: Request, q: str = Query(min_length=2, max_length=100), user=
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
|
||||
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
|
||||
orders = visible(request, with_print_files(c, orders))
|
||||
orders = with_print_files(c, orders)
|
||||
quotes = [quote_view(c, row) for row in rows]
|
||||
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes)}
|
||||
@@ -636,8 +627,11 @@ class MachineChoice(StrictModel):
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/machine')
|
||||
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))):
|
||||
"""Send an order to a machine, or back to the automatic choice (None)."""
|
||||
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)."""
|
||||
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.')
|
||||
@@ -812,11 +806,15 @@ 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 FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
row = c.execute('SELECT state, machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Order not found')
|
||||
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']
|
||||
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
|
||||
and (not mine or str(row['machine_id'] or '') != mine['id'])):
|
||||
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
|
||||
keys = {}
|
||||
for side in ('after', 'before'):
|
||||
other = getattr(body, side)
|
||||
@@ -860,6 +858,25 @@ 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.
|
||||
account = request.state.operator
|
||||
session_machine = account['machine']
|
||||
pulling = row['state'] == 'tra' and body.state == 'imp'
|
||||
if account['role'] == 'operador':
|
||||
if not session_machine:
|
||||
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.')
|
||||
if pulling and session_machine 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.")
|
||||
# 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
|
||||
@@ -873,8 +890,14 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
||||
if body.state == 'cor':
|
||||
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))
|
||||
# Who moved it, and on which machine: the one it goes to print on, or
|
||||
# else the mover's.
|
||||
machine_name = (session_machine or {}).get('name')
|
||||
if body.state == 'imp' and row['machine_id']:
|
||||
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
|
||||
(row['machine_id'],)).fetchone() or {}).get('name')
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
|
||||
# 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,
|
||||
@@ -1258,12 +1281,11 @@ def named_files(rows):
|
||||
return files
|
||||
|
||||
|
||||
def print_ready(c, request, states, only=None, paid_after=None):
|
||||
def print_ready(c, states, only=None, paid_after=None):
|
||||
"""The file to print for each item of the orders in these stages, in queue
|
||||
order: the approved final, or before approval the generated print file
|
||||
(unless the customer has sent a correction since). `only` narrows it to
|
||||
these orders, `paid_after` to the orders paid since then. An operator who
|
||||
works on some machines gets only those machines' orders."""
|
||||
these orders, `paid_after` to the orders paid since then."""
|
||||
ids = None if only is None else list(only)
|
||||
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
|
||||
@@ -1284,32 +1306,28 @@ def print_ready(c, request, states, only=None, paid_after=None):
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
|
||||
ORDER BY position,order_id,item_index''',
|
||||
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
|
||||
# Only the orders that have a file, for their machines: not every order in the stages.
|
||||
staged = assign_machines(c, c.execute('SELECT * FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
(list({row['order_id'] for row in rows}),)).fetchall())
|
||||
mine = {o['id'] for o in visible(request, staged)}
|
||||
return [row for row in rows if row['order_id'] in mine]
|
||||
return rows
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/{uid}/folder-files')
|
||||
def folder_files(uid: UUID, request: Request, user=Depends(can('produce'))):
|
||||
def folder_files(uid: UUID, user=Depends(can('produce'))):
|
||||
"""What each item's file is called in the order's stage folder, as the
|
||||
automatic folders save it: "Tratar a arte" shows where to open it."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
files = named_files(print_ready(c, request, (row['state'],), only=[uid]))
|
||||
files = named_files(print_ready(c, (row['state'],), only=[uid]))
|
||||
return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]}
|
||||
|
||||
|
||||
@router.get('/api/operator/queue/finals')
|
||||
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
|
||||
def queue_finals(auto: bool = False, user=Depends(can('print'))):
|
||||
"""The approved final files of every order in the print queue (Arte
|
||||
conferida). The browser downloads them straight from storage: a zip of
|
||||
multi-GB sheets would go through the server."""
|
||||
with db.connect() as c:
|
||||
files = named_files(print_ready(c, request, ('tra',)))
|
||||
files = named_files(print_ready(c, ('tra',)))
|
||||
# The automatic folder asks whenever the queue changes; only a person's download is logged.
|
||||
if not auto:
|
||||
audit('queue_finals_downloaded', operator=user, files=len(files))
|
||||
@@ -1325,7 +1343,7 @@ class FolderSync(StrictModel):
|
||||
|
||||
|
||||
@router.post('/api/operator/queue/folder')
|
||||
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
|
||||
def queue_folder(body: FolderSync, user=Depends(can('print'))):
|
||||
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
|
||||
stage folders (2026-10-26): the files of orders in Arte recebida and Arte
|
||||
conferida, and, for the orders the folders already hold, their files while
|
||||
@@ -1338,12 +1356,12 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print')))
|
||||
folders hold files of: a stage, 'cancelled', or nothing when the order was
|
||||
deleted, so their files can be removed."""
|
||||
with db.connect() as c:
|
||||
rows = print_ready(c, request, ('rec', 'tra') if body.early else ('tra',))
|
||||
rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',))
|
||||
if body.early and body.held:
|
||||
rows += print_ready(c, request, ('imp', 'rev', 'fin'), only=body.held)
|
||||
rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held)
|
||||
if body.early and body.since:
|
||||
seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows}
|
||||
rows += [r for r in print_ready(c, request, ('imp', 'rev', 'fin'), paid_after=body.since)
|
||||
rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since)
|
||||
if (r['order_id'], r['item_index'], r['upload_id']) not in seen]
|
||||
files = named_files(rows)
|
||||
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
|
||||
Reference in New Issue
Block a user