"""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, machine_stats from ..core import db from ..core.auth import audit, can, operator from ..core.models import MachineEntry, MachineSheet router = APIRouter() # Números is read by management and by the seller and finance, who consult it. STATS_ROLES = ('superadmin', 'admin', 'gestao', 'vendedor', 'financeiro') 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} @router.get('/api/operator/stats/machines') def machine_stats_month(request: Request, month: str | None = None, user=Depends(operator)): """Números per machine, month by month (Fase 2, front 1b).""" if request.state.operator['role'] not in STATS_ROLES: raise HTTPException(403, 'Seu perfil não permite esta ação.') try: start, _ = machine_stats.month_bounds(month) except ValueError: raise HTTPException(422, 'Informe o mês como AAAA-MM.') if start > machine_stats.month_bounds(None)[0]: raise HTTPException(422, 'Esse mês ainda não começou.') with db.connect() as c: return machine_stats.report(c, month=month)