All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m20s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m11s
The machine's name in Imprimindo (and "Ficha" in Usuários › Máquinas) opens its sheet: metres since the last cleaning and since the last film change, each supply's estimate, pending alerts and the entries. The room enters supplies (film, ink by colour, powder; a supply without cost takes the last one), parts (cap, damper, head, wiper, other) and events (cleaning, head alignment, a stop with reason and minutes). Gestão types the price, installation date and supply minimums. Alerts appear when someone pulls the next card onto the machine, never mid-print: 10 m since the last cleaning, 20 m after a film change without aligning the head, and a supply at its minimum. Marked done it records the event; postponed once it lets one more card through. The server refuses the pull otherwise. Counters start when the sheet went live (machines.log_since), not from everything printed before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
120 lines
5.4 KiB
Python
120 lines
5.4 KiB
Python
"""Routes of the machine sheet (Fase 2, front 1a, app/machine_log.py)."""
|
|
from uuid import UUID
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
|
|
from .. import machine_log
|
|
from ..core import db
|
|
from ..core.auth import audit, can
|
|
from ..core.models import MachineEntry, MachineSheet
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def machine_row(c, mid):
|
|
row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s',
|
|
(mid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Máquina não encontrada.')
|
|
return row
|
|
|
|
|
|
def own_machine(request, mid):
|
|
"""An operator enters only on the machine of their session; management, anywhere."""
|
|
account = request.state.operator
|
|
if account['role'] != 'operador':
|
|
return
|
|
session_machine = account['machine']
|
|
if not session_machine or str(session_machine['id']) != str(mid):
|
|
raise HTTPException(403, 'Você só lança na máquina em que está.')
|
|
|
|
|
|
def entry_label(row):
|
|
if row['kind'] == 'supply':
|
|
return machine_log.SUPPLIES.get(row['item'], (row['item'],))[0]
|
|
if row['kind'] == 'part':
|
|
return machine_log.PARTS.get(row['item'], row['item'])
|
|
return machine_log.EVENTS.get(row['item'], row['item'])
|
|
|
|
|
|
@router.get('/api/operator/machines/{mid}/sheet')
|
|
def sheet(mid: UUID, user=Depends(can('view'))):
|
|
with db.connect() as c:
|
|
machine = machine_row(c, mid)
|
|
entries = c.execute('''SELECT * FROM dtf_local.machine_entries
|
|
WHERE machine_id=%s ORDER BY created_at DESC, id DESC LIMIT 50''', (mid,)).fetchall()
|
|
minimums = {row['item']: row['minimum'] for row in c.execute(
|
|
'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (mid,)).fetchall()}
|
|
return {'machine': {'id': str(machine['id']), 'name': machine['name'],
|
|
'price_cents': machine['price_cents'], 'installed_on': machine['installed_on']},
|
|
'counters': machine_log.counters(c, mid),
|
|
'supplies': machine_log.supply_estimates(c, mid),
|
|
'minimums': minimums,
|
|
'alerts': machine_log.alerts(c, mid),
|
|
'entries': [{**row, 'label': entry_label(row)} for row in entries],
|
|
'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS,
|
|
'events': machine_log.EVENTS}}
|
|
|
|
|
|
@router.post('/api/operator/machines/{mid}/entries')
|
|
def add_entry(mid: UUID, body: MachineEntry, request: Request, user=Depends(can('print'))):
|
|
own_machine(request, mid)
|
|
catalog = {'supply': machine_log.SUPPLIES, 'part': machine_log.PARTS,
|
|
'event': machine_log.EVENTS}[body.kind]
|
|
if body.item not in catalog:
|
|
raise HTTPException(422, 'Escolha um item da lista.')
|
|
if body.kind == 'supply':
|
|
if body.quantity is None:
|
|
raise HTTPException(422, 'Informe a quantidade que entrou.')
|
|
elif body.kind == 'part':
|
|
if body.cost_cents is None:
|
|
raise HTTPException(422, 'Informe o custo da peça.')
|
|
if body.item == 'other' and not (body.note or '').strip():
|
|
raise HTTPException(422, 'Descreva a outra peça.')
|
|
elif body.item == 'stop':
|
|
if not (body.note or '').strip() or body.stop_minutes is None:
|
|
raise HTTPException(422, 'Informe o motivo e os minutos da parada.')
|
|
elif body.quantity is not None or body.cost_cents is not None:
|
|
raise HTTPException(422, 'Limpeza e alinhamento não levam quantidade nem custo.')
|
|
with db.connect() as c:
|
|
machine_row(c, mid)
|
|
row = machine_log.add_entry(c, mid, body, user, from_alert=body.from_alert)
|
|
audit('machine_entry', operator=user, machine=str(mid), kind=body.kind, item=body.item,
|
|
from_alert=body.from_alert)
|
|
return row
|
|
|
|
|
|
@router.post('/api/operator/machines/{mid}/sheet')
|
|
def save_sheet(mid: UUID, body: MachineSheet, user=Depends(can('manage'))):
|
|
unknown = set(body.minimums) - set(machine_log.SUPPLIES)
|
|
if unknown:
|
|
raise HTTPException(422, 'Só os insumos têm mínimo.')
|
|
for value in body.minimums.values():
|
|
if value is not None and value < 0:
|
|
raise HTTPException(422, 'O mínimo não pode ser negativo.')
|
|
with db.connect() as c:
|
|
machine_row(c, mid)
|
|
c.execute('UPDATE dtf_local.machines SET price_cents=%s, installed_on=%s WHERE id=%s',
|
|
(body.price_cents, body.installed_on, mid))
|
|
for item, value in body.minimums.items():
|
|
if value is None:
|
|
c.execute('DELETE FROM dtf_local.machine_minimums WHERE machine_id=%s AND item=%s',
|
|
(mid, item))
|
|
else:
|
|
c.execute('''INSERT INTO dtf_local.machine_minimums(machine_id,item,minimum)
|
|
VALUES(%s,%s,%s) ON CONFLICT (machine_id,item) DO UPDATE SET minimum=EXCLUDED.minimum''',
|
|
(mid, item, value))
|
|
audit('machine_sheet', operator=user, machine=str(mid), price_cents=body.price_cents,
|
|
installed_on=str(body.installed_on) if body.installed_on else None)
|
|
return {'ok': True}
|
|
|
|
|
|
@router.post('/api/operator/machines/{mid}/alerts/{key}/snooze')
|
|
def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'))):
|
|
own_machine(request, mid)
|
|
with db.connect() as c:
|
|
machine_row(c, mid)
|
|
machine_log.snooze(c, mid, key, user)
|
|
audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key)
|
|
return {'ok': True}
|