Order #20 (23.6 m, 24 pieces) failed with "Falhou ao gerar": the whole film had one 15 min limit, and two parts at 300 DPI take longer on the server. The limit is now PRINT_RENDER_TIMEOUT_SECONDS (default 20 min) for each part, and each claim records its deadline, so the stale-claim check and the card's "Tempo limite" follow the same limit. A timeout, or a final failed attempt, is logged as an error so Sentry sees it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
276 lines
17 KiB
Python
276 lines
17 KiB
Python
"""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 COALESCE(p.deadline_at,p.claimed_at+%s)<now()) AS timed_out,
|
|
COALESCE(p.deadline_at,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''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
|
|
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']
|
|
for uid in item.get('uploads') or []})
|
|
uploads = {row['id']: row for row in c.execute(
|
|
'''SELECT id::text AS id,name,original_name FROM dtf_local.uploads WHERE id::text=ANY(%s)''',
|
|
(upload_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()
|
|
for row in generated:
|
|
row['parts'] = [{'upload_id': part['upload_id'], 'name': part['name']} for part in parts
|
|
if part['order_id'] == row['order_id'] and part['item_index'] == row['item_index']]
|
|
finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f
|
|
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
|
|
# Expired ones too: once corrected, a generated file is no longer the artwork.
|
|
fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name,
|
|
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
|
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
|
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
|
# The items whose approved final someone prepared, and who approved it.
|
|
treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f
|
|
JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED}
|
|
ORDER BY f.item_index''', (ids,)).fetchall()
|
|
# Each order's reworks (D-02 to D-04), with the names of who opened,
|
|
# decided and printed.
|
|
reworks = c.execute(f'''SELECT r.*, {person('r.opened_by')} AS opened_name, {person('r.decided_by')} AS decided_name,
|
|
{person('r.printed_by')} AS printed_name FROM dtf_local.reworks r WHERE r.order_id=ANY(%s) ORDER BY r.id''',
|
|
(ids,)).fetchall()
|
|
# Why each order was last sent to correction, for the notice to the customer.
|
|
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
|
# Where a printing order's files are in its machine's hot folder (item 10).
|
|
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
|
# Each parent's latest proof card, and each card's parent (app/proof.py).
|
|
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
|
|
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
|
|
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
|
|
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
|
|
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
|
|
# Every order's review photos and videos, in one query like the print files.
|
|
review_rows = reviews.by_order(c, ids)
|
|
for order in orders:
|
|
order['hot'] = hot.get(order['id'])
|
|
order['reviews'] = review_rows.get(str(order['id']), [])
|
|
child = children.get(order['id'])
|
|
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
|
|
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
|
|
parent = parents.get(order.get('parent_id'))
|
|
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
|
|
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
|
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
|
order['prumo'] = prumo.report(order, uploads)
|
|
approved = [row for row in finals if row['order_id'] == order['id']]
|
|
order['final_items'] = sorted({row['item_index'] for row in approved})
|
|
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.
|
|
order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved]
|
|
mine = [row for row in treated if row['order_id'] == order['id']]
|
|
order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None
|
|
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
|
for row in fixes if row['order_id'] == order['id']]
|
|
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
|
|
return assign_machines(c, orders)
|
|
|
|
|
|
@router.get('/api/operator/orders/finished')
|
|
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_finished_at, before_id)
|
|
with db.connect() as c:
|
|
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)}
|
|
|
|
|
|
@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'})
|