"""The board, its stage limits, and the finished orders beyond it.""" from datetime import datetime, timezone from decimal import Decimal from typing import Literal from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query, Response from pydantic import Field from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews from ...cart_pricing import designer_hours from ...core import db from ...core.auth import audit, can, operator from ...core.models import StrictModel from ...printjobs import CLAIM_TIMEOUT from ...runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, quote_views) from .common import (FINAL_OK, LIVE_QUOTE, TREATED, company_names, cursor_pair, person, thumbnails) from .integrations import backup_status, freight_status, tiny_status router = APIRouter() @router.get('/api/operator/board') def board(user=Depends(operator)): with db.connect() as c: limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} for row in c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()} # 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 ( 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 WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE} ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall() approved = c.execute(f'''SELECT q.* 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} ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall() pending_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 NULL AND {LIVE_QUOTE}''').fetchone()['n'] 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 + finished) assign_late(c, orders, limits) # 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. issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n'] backup = backup_status(c) quotes = quote_views(c, pending + approved) return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK, 'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(c), 'operator': user, 'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup, 'mail': mail.status(c)}, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN, 'finished_shown': len(finished), 'finished_total': finished_total, # Who is on each machine now, for the machine question (item 12). 'machines': machines.rows(c, with_operators=True), '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, 'stage_limits': limits} class StageLimit(StrictModel): state: Literal['rec', 'tra', 'imp', 'rev', 'fin'] hours: Decimal = Field(gt=0, le=10000) responsible: str = Field(default='', max_length=80) class StageLimits(StrictModel): limits: list[StageLimit] = Field(min_length=1, max_length=5) @router.get('/api/operator/stage-limits') def get_stage_limits(user=Depends(operator)): with db.connect() as c: rows = c.execute('''SELECT state,hours,responsible,updated_by,updated_at FROM dtf_local.stage_limits ORDER BY array_position(ARRAY['rec','tra','imp','rev','fin'],state)''').fetchall() return {'limits': [{'state': row['state'], 'hours': float(row['hours']), 'responsible': row['responsible'], 'updated_by': row['updated_by'], 'updated_at': row['updated_at']} for row in rows]} @router.post('/api/operator/stage-limits') def set_stage_limits(body: StageLimits, user=Depends(can('manage'))): seen = set() with db.connect() as c: for limit in body.limits: if limit.state in seen: raise HTTPException(422, 'Cada etapa aparece uma vez.') seen.add(limit.state) c.execute('''INSERT INTO dtf_local.stage_limits(state,hours,responsible,updated_by,updated_at) VALUES(%s,%s,%s,%s,now()) ON CONFLICT (state) DO UPDATE SET hours=EXCLUDED.hours,responsible=EXCLUDED.responsible, updated_by=EXCLUDED.updated_by,updated_at=now()''', (limit.state, limit.hours, limit.responsible.strip(), user)) audit('stage_limits_changed', operator=user, states=','.join(sorted(seen))) return {'ok': True} def assign_late(c, orders, limits): """How long each card has been in its stage, and whether it passed the limit Gestão set (front 11). A finished card with pickup is not late.""" ids = [order['id'] for order in orders] if not ids: return entered = {} for row in c.execute('''SELECT order_id,to_state,created_at FROM dtf_local.movements WHERE order_id=ANY(%s) ORDER BY created_at,id''', (ids,)).fetchall(): entered[(str(row['order_id']), row['to_state'])] = row['created_at'] now = datetime.now(timezone.utc) for order in orders: if order.get('cancelled_at') or payments.is_test(order): continue limit = limits.get(order['state']) if not limit: continue # Finalizado only has a pickup deadline; a delivery is done when it # leaves, and a collected order is not waiting for anyone. if order['state'] == 'fin' and (order.get('picked_up_at') or not receipt.is_pickup(order['snapshot'])): continue since = entered.get((str(order['id']), order['state'])) if not since and order['state'] == 'fin': since = order.get('finished_at') since = since or order['created_at'] hours = max(0.0, (now - since).total_seconds() / 3600) limit_hours = float(limit['hours']) # Paid designer work gives Art received its extra hours to prepare the # art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino. if order['state'] == 'rec': limit_hours += designer_hours(order.get('snapshot') or {}) order['state_hours'] = round(hours, 2) order['limit_hours'] = limit_hours order['limit_by'] = limit['responsible'] order['late'] = 'bad' if hours >= limit_hours * 2 else 'warn' if hours >= limit_hours else None def assign_machines(c, orders): """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 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,p.claimed_at,p.finished_at, p.created_at, (p.status='rendering' AND p.claimed_at limit, 'thumbnails': thumbnails(c, orders), 'names': company_names(c, orders)} @router.get('/api/operator/orders/{uid}/history') def history(uid: UUID, user=Depends(operator)): with db.connect() as c: return c.execute('SELECT * FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (uid,)).fetchall() @router.get('/api/operator/uploads/{uid}/thumbnail') def thumbnail(uid: UUID, user=Depends(operator)): """The browser-made picture of an artwork. Cached by the operator's browser: the board is redrawn on every refresh.""" with db.connect() as c: row = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)).fetchone() if not row: raise HTTPException(404, 'No picture for this upload') return Response(bytes(row['data']), media_type=row['mime'], headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})