"""Kanban: sign-in, the board, commercial review and card movement.""" import hashlib import os import re import secrets from decimal import Decimal from datetime import date, datetime, timedelta, timezone from typing import Literal from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from fastapi.responses import RedirectResponse from pydantic import Field from ..core import db from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator, login_failed, may_move, may_reorder, password_matches, throttle) from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..printjobs import file_prefix, queue as queue_print_files from .. import cnpj, machines, mail, payments, proof, quote_review from .. import tiny from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, enqueue, freight, quote_view, storage) from ..scanning import require_clean router = APIRouter() # A quote that can still become an order: waiting for review, or approved within # the payment window. Expired ones leave the Kanban; they can never be paid. LIVE_QUOTE = (f"(q.discarded_at IS NULL AND (q.approved_at IS NULL OR " f"q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours'))") @router.post('/api/operator/login') def operator_login(body: OperatorLogin, request: Request, response: Response): email = body.email throttle('operator:'+email, request) with db.connect() as c: account = c.execute('SELECT * FROM dtf_local.operators WHERE email=%s', (email,)).fetchone() if not c.execute('SELECT 1 FROM dtf_local.operators WHERE active LIMIT 1').fetchone(): raise HTTPException(503, 'Nenhuma conta de operador configurada.') # Comparable password work whether or not the account exists or is active. stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH matches = password_matches(body.password, stored) if not account or not account['active'] or not matches: login_failed('operator:'+email) audit('operator_login_failed', ip=client_ip(request), operator=email) raise HTTPException(401, 'E-mail ou senha inválidos.') token = secrets.token_urlsafe(32) with db.connect() as c: previous = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest() c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (previous,)) c.execute('INSERT INTO dtf_local.operator_sessions(token_hash,username) VALUES(%s,%s)', (hashlib.sha256(token.encode()).hexdigest(), email)) c.execute('UPDATE dtf_local.operators SET last_login_at=now() WHERE id=%s', (account['id'],)) response.set_cookie('dtf_operator', token, httponly=True, secure=COOKIE_SECURE, samesite='strict', path='/api/operator', max_age=28800) audit('operator_login_success', operator=email) return {'ok': True} @router.post('/api/operator/logout') def operator_logout(request: Request, response: Response): with db.connect() as c: digest = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest() c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (digest,)) response.delete_cookie('dtf_operator', path='/api/operator', httponly=True, secure=COOKIE_SECURE, samesite='strict') audit('operator_logout') return {'ok': True} def freight_status(): """What delivery the Site offers, and the package rule it prices with.""" real = [carrier for carrier in freight.carriers if carrier.name != 'fake'] status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}} if real: # One package for every carrier (app/package.py). status.update(real[0].status()) return status def backup_status(c): """The latest database backup and the latest run, which may have failed.""" ok = c.execute('''SELECT finished_at,bytes FROM dtf_local.backups WHERE status='ok' ORDER BY finished_at DESC LIMIT 1''').fetchone() last = c.execute('SELECT started_at,finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone() asked = c.execute('''SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1''', (last['started_at'] if last else datetime(2000, 1, 1, tzinfo=timezone.utc),)).fetchone() return {'last_ok': ok['finished_at'].isoformat() if ok else None, 'bytes': ok['bytes'] if ok else None, 'failed': last['detail'] if last and last['status'] == 'failed' else None, 'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None, 'requested': asked is not None} @router.post('/api/operator/backup/run') def backup_now(user=Depends(can('integrations'))): """A backup now, outside the daily hour: the backup service, which alone may read the whole database, starts it within a minute.""" with db.connect() as c: c.execute('INSERT INTO dtf_local.backup_requests(requested_by) VALUES(%s)', (user,)) audit('backup_requested', operator=user) return {'ok': True} @router.get('/api/operator/board') def board(request: Request, 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) # 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() finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s", (BOARD_FINISHED_LIMIT,)).fetchall() finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").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 = visible(request, 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. 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_view(c, q) for q in pending + approved] return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK, 'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), '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, 'machines': machines.rows(c), '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} def uploads_of(rows): """Every upload id an order (its snapshot) or a quote (its draft) refers to.""" ids = set() for row in rows: content = row.get('snapshot') or row.get('draft') or {} for item in content.get('items') or []: ids.update(str(uid) for uid in item.get('uploads') or []) return ids def thumbnails(c, *groups): """The uploads among these orders and quotes that have an artwork picture, so the Kanban asks only for pictures that exist.""" ids = set().union(*(uploads_of(rows) for rows in groups)) if not ids: return [] rows = c.execute('SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s::uuid[])', (list(ids),)).fetchall() return [str(r['upload_id']) for r in rows] def company_names(c, *groups): """The registry's company names for these orders' and quotes' CNPJs (app/cnpj.py).""" return cnpj.names(c, [((row.get('snapshot') or row.get('draft') or {}).get('customer') or {}).get('cnpj') for rows in groups for row in rows]) # An item's final counts while its file is still there and scanned clean: the # same rule that lets an order into the print queue. FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'""" # "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the # customer's own artwork. It is neither the file the system generated from # their art, nor one of their originals, nor a correction they sent. `f` is # the final in dtf_local.order_files, `o` its order. TREATED = """f.kind='final' AND NOT EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id AND k.kind='correction')""" def assign_machines(c, orders): """Each order's machine as stored (app/machines.py gives it): chosen by someone, or automatic. None while no machine prints its product. In Imprimindo, also which of its machine's two places it holds.""" names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()} slots = machines.printing_slots(c) 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']) 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.""" ids = [o['id'] for o in orders] generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,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''', (ids,)).fetchall() 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()} for order in orders: 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']] 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) def person(column): """SQL: the team member's name for the e-mail in `column`, or the e-mail.""" return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})' def cursor_pair(first, second): if (first is None) != (second is None): raise HTTPException(422, 'Both cursor fields are required') return first is not None @router.get('/api/operator/orders/finished') def finished_page(request: Request, 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) with db.connect() as c: rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' ''' + ('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])) return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders), 'names': company_names(c, orders)} @router.get('/api/operator/payment-events') def payment_events(state: Literal['open','resolved','all'] = 'open', offset: int = Query(default=0, ge=0), limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))): """Payments that needed a person, newest first: open ones to act on, resolved ones as history.""" where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state] with db.connect() as c: rows = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome, resolved_at,resolved_by,resolution FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') ''' + where + ''' ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall() total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n'] return {'issues': rows, 'total': total} @router.get('/api/operator/events') def events(provider: Literal['tiny'] | None = None, status: Literal['delivered','queued','failing'] | None = None, event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None, order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0), limit: int = Query(default=20, ge=1, le=100), user=Depends(can('integrations'))): """The integration send log, newest first, filtered, by page with a total.""" clauses, params = [], [] if provider: clauses.append('provider=%s'); params.append(provider) if status == 'delivered': clauses.append('delivered_at IS NOT NULL') elif status == 'queued': clauses.append('delivered_at IS NULL AND last_error IS NULL') elif status == 'failing': clauses.append('delivered_at IS NULL AND last_error IS NOT NULL') if event: clauses.append("payload->>'event'=%s"); params.append(event) if order: clauses.append("payload->>'number'=%s"); params.append(str(order)) where = ('WHERE ' + ' AND '.join(clauses)) if clauses else '' with db.connect() as c: rows = c.execute(f'SELECT * FROM dtf_local.outbox {where} ORDER BY id DESC LIMIT %s OFFSET %s', (*params, limit, offset)).fetchall() total = c.execute(f'SELECT count(*) AS n FROM dtf_local.outbox {where}', params).fetchone()['n'] return {'events': rows, 'total': total} MODES = {'textil': {'file', 'avulsa'}, 'uv': {'uvfile', 'uv'}, 'folha': {'file', 'uvfile'}, 'avulsa': {'avulsa', 'uv'}} def like(text): """A LIKE pattern that matches the text anywhere, its own % and _ literal.""" return '%' + re.sub(r'([\\%_])', r'\\\1', text) + '%' def numeric(q): """The digits of a query made of digits and punctuation only ("#1042", "11.222.333/0001-81", "(16) 99999-0000"); empty when it has letters.""" return '' if re.search(r'[^\W\d_]', q) else re.sub(r'\D', '', q) def customer_match(column, q): """SQL and parameters matching a customer (e-mail, company name, CNPJ or WhatsApp) in an order snapshot or a quote draft. CNPJ and phone match by their digits, and only when nothing but digits and punctuation was typed: the digits of an e-mail address are not a phone number.""" text, digits = q.strip().lower(), numeric(q) cnpj = f"regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g')" sql = (f"lower({column}->'customer'->>'mail') LIKE %s OR {cnpj} IN (SELECT n.cnpj FROM dtf_local.cnpj_names n" " WHERE lower(n.legal_name) LIKE %s OR lower(n.trade_name) LIKE %s)") params = [like(text)] * 3 if len(digits) >= 3: sql += (f" OR regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g') LIKE %s" f" OR regexp_replace(coalesce({column}->'customer'->>'zap',''),'\\D','','g') LIKE %s") params += [like(digits), like(digits)] return '(' + sql + ')', params @router.get('/api/operator/quotes') def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None, before_id: UUID | None = None, offset: int = Query(default=0, ge=0), limit: int = Query(default=50, ge=1, le=100), q: str | None = Query(default=None, max_length=100), product: Literal['textil','uv'] | None = None, layout: Literal['folha','avulsa'] | None = None, flag: Literal['ressalva'] | None = None, user=Depends(operator)): """Unpaid quotes, newest first: by cursor, or by page (offset) with a total; filtered by customer, product, layout and an accepted resolution warning.""" if (before_created_at is None) != (before_id is None): raise HTTPException(422, 'Both quote cursor fields are required') clauses = ['o.id IS NULL', LIVE_QUOTE, 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL'] params = [] if q and q.strip(): sql, values = customer_match('q.draft', q) clauses.append(sql); params += values if product or layout: modes = set.intersection(*(MODES[k] for k in (product, layout) if k)) clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'mode'=ANY(%s))") params.append(sorted(modes)) if flag: clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'quality_status'='warning')") where = ' AND '.join(clauses) cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else '' skip = 0 if before_created_at else offset page = params + ([before_created_at, before_id] if before_created_at else []) + [limit+1, skip] with db.connect() as c: rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE {where} {cursor} ORDER BY q.created_at DESC,q.id DESC LIMIT %s OFFSET %s''', page).fetchall() 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 {where}''', params).fetchone()['n'] quotes = [quote_view(c,row) for row in rows[:limit]] return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total, 'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)} @router.get('/api/operator/search') def search(request: Request, 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) digits = numeric(q) sql = match + " OR lower(coalesce(snapshot->'destination'->>'recipient','')) LIKE %s" params.append(like(q.strip().lower())) if digits and len(digits) <= 9: sql += ' OR number=%s' params.append(int(digits)) # The code a customer reads out (the id's first characters, see order_code). code = q.strip().lstrip('#').lower() if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code): sql += " OR replace(id::text,'-','') LIKE %s" params.append(code + '%') quote_match, quote_params = customer_match('q.draft', q) with db.connect() as c: orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql} ORDER BY created_at DESC LIMIT 8''', params).fetchall() rows = 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 {LIVE_QUOTE} AND {quote_match} ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall() orders = visible(request, 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)} @router.post('/api/operator/quotes/{uid}/approve') def approve(uid: UUID, body: Review, user=Depends(can('manage'))): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Quote not found') return quote_review.approve(c, row, body.items, user) @router.post('/api/operator/quotes/{uid}/test-order') def test_order(uid: UUID, user=Depends(can('manage'))): """An order for an approved quote without payment, to try the Kanban, files and print flow in production. Marked TEST on the board, never sent to Tiny or WhatsApp, and audited.""" with db.connect() as c: try: quote = payments.approved_quote(c, uid) except payments.PaymentRefused as refusal: raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal)) receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} order, created = payments.create_order(c, quote, receipt, 'site') if created: audit('test_order_created', order=str(order['id']), operator=user) return order class PaidOutside(StrictModel): # No defaults (D-35): whoever registers the order says where it came from # and how it was paid. origin: Literal['site', 'dropflow', 'atendimento'] method: Literal[payments.OUTSIDE_METHODS] note: str = Field(default='', max_length=300) @router.post('/api/operator/quotes/{uid}/register') def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))): """The order for an approved quote paid outside the system (Dropstar's rule D-35): the team builds the cart on the Site, as a customer would, and registers it here with its origin and how it was paid. The price is the quote's, the Site's table price.""" with db.connect() as c: try: quote = payments.approved_quote(c, uid) except payments.PaymentRefused as refusal: raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal)) receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(), 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} order, created = payments.create_order(c, quote, receipt, body.origin) if not created: raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.") audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user) return order # Rework (Dropstar's rules D-02 to D-04): four causes of the house, each with a # goal of 0,4% of the film printed (1,6% in all), and the customer's approved # bad art, recorded apart and outside the goal (D-04). HOUSE_CAUSES = ('impressao', 'perfil_cor', 'tratamento', 'pedido') CUSTOMER_CAUSE = 'arte_cliente' REWORK_GOAL_PERCENT = Decimal('0.4') class ReworkOpen(StrictModel): cause: Literal[HOUSE_CAUSES + (CUSTOMER_CAUSE,)] metres: Decimal = Field(gt=0, le=1000) note: str = Field(default='', max_length=1000) class ReworkDecision(StrictModel): authorized: bool reason: str = Field(default='', max_length=1000) @router.post('/api/operator/orders/{uid}/reworks') def open_rework(uid: UUID, body: ReworkOpen, user=Depends(can('rework'))): """Coordination opens a rework with its cause (D-02). There is no way to change the cause afterwards (D-03).""" with db.connect() as c: order = c.execute('SELECT id,number,cancelled_at FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() if not order: raise HTTPException(404, 'Pedido não encontrado.') if order['cancelled_at']: raise HTTPException(409, 'Pedido cancelado não abre retrabalho.') # Who printed the sheet: who last sent it to Revisão. printed = c.execute('''SELECT operator FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone() row = c.execute('''INSERT INTO dtf_local.reworks(order_id,cause,metres,note,printed_by,opened_by) VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''', (uid, body.cause, body.metres, body.note.strip(), printed['operator'] if printed else None, user)).fetchone() audit('rework_opened', order=order['number'], cause=body.cause, operator=user) return row @router.post('/api/operator/reworks/{rid}/decision') def decide_rework(rid: int, body: ReworkDecision, user=Depends(can('authorize'))): """An Administrador authorizes a rework, and only then it counts, or declines it with a reason (D-02). Never one they opened themselves.""" reason = body.reason.strip() if not body.authorized and len(reason) < 3: raise HTTPException(422, 'Diga por que o retrabalho não foi autorizado.') with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.reworks WHERE id=%s FOR UPDATE', (rid,)).fetchone() if not row: raise HTTPException(404, 'Retrabalho não encontrado.') if row['decided_at']: raise HTTPException(409, 'Este retrabalho já foi decidido.') if row['opened_by'] == user: raise HTTPException(409, 'Quem abriu o retrabalho não pode autorizá-lo.') row = c.execute('''UPDATE dtf_local.reworks SET authorized=%s, decided_by=%s, decided_at=now(), decline_reason=%s WHERE id=%s RETURNING *''', (body.authorized, user, None if body.authorized else reason, rid)).fetchone() audit('rework_decided', rework=rid, authorized=body.authorized, operator=user) return row @router.post('/api/operator/quotes/{uid}/discard') def discard_quote(uid: UUID, user=Depends(can('manage'))): """An unpaid quote leaves the Kanban and can no longer be paid. Its files keep their normal expiry; a payment that still arrives for it is refused and listed under Pagamentos.""" with db.connect() as c: # Locked like a payment locks it, so a discard and a payment never cross. row = c.execute('SELECT id FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Quote not found') if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (uid,)).fetchone(): raise HTTPException(409, 'Esta cotação já virou pedido.') c.execute('UPDATE dtf_local.quotes SET discarded_at=now(), discarded_by=%s WHERE id=%s AND discarded_at IS NULL', (user, uid)) audit('quote_discarded', quote=str(uid), operator=user) return {'ok': True} @router.post('/api/operator/orders/{uid}/delete') def delete_order(uid: UUID, user=Depends(can('manage'))): """Deletes a test order, or a paid order already cancelled, with its history and files' records. A paid order in progress must be cancelled first, with its reason. A test order's quote is unpaid again; a cancelled one's is discarded, so it neither returns to Cotações nor can be paid twice. The payment itself stays recorded, and the audit log keeps who deleted what.""" with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') test = payments.is_test(row) if not test and not row.get('cancelled_at'): raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.') # Its files leave storage too: the finals, corrections and generated PDFs, # and the customer's originals unless the quote can still be paid (a test # order's). The worker deletes them within a minute. originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []} produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''', (uid, uid)).fetchall()} candidates = produced - originals if test else produced | originals for table in ('movements', 'order_files', 'print_files'): c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,)) c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,)) if not test: c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s', (user, row['quote_id'])) freed = release_files(c, candidates) audit('order_deleted', order=row['number'], test=test, operator=user, reason=row.get('cancel_reason') or '', files_released=freed) return {'ok': True} def release_files(c, uploads): """Expire these uploads now, except any another order or an open quote still uses: a customer can buy the same file again. Returns how many.""" free = [] for upload in uploads: used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? %s UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id) AND i->'uploads' ? %s LIMIT 1''', (upload, upload, upload, upload)).fetchone() if not used: free.append(upload) if free: c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[]) AND purged_at IS NULL''', (free,)) return len(free) @router.post('/api/operator/orders/{uid}/cancel') def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))): """A paid order leaves the board but keeps its payment and history. Nothing is refunded here (that is done at the provider); Tiny is told, so the order is cancelled there too while it was not invoiced (app/tiny.py).""" with db.connect() as c: row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s, version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING *''', (user, body.note, uid)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado ou já cancelado.') if payments.in_tiny(row): sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", (f'{uid}:paid:tiny',)).fetchone() enqueue(c, f'{uid}:cancelled:tiny', 'tiny', {'order_id': str(uid), 'number': row['number'], 'event': 'cancelled', 'reason': body.note, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}) audit('order_cancelled', order=row['number'], operator=user) return {'ok': True} class MachineChoice(StrictModel): machine_id: UUID | None = None @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).""" 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.') row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado.') machines.route(c) # Printing already: the machine it goes to must have a place in Imprimindo. if row['state'] == 'imp' and not row['cancelled_at']: now = c.execute('SELECT machine_id FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() if name := machines.full(c, now['machine_id'], uid): raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user) return {'ok': True} class ContactWait(StrictModel): waiting: bool note: str = Field(default='', max_length=500) @router.post('/api/operator/orders/{uid}/contact') def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))): """Mark an order as waiting for a word with the customer, with what has to be agreed, or clear the mark once that is done. The stage does not change and the customer is not told.""" note = ' '.join(body.note.split()) if body.waiting and len(note) < 3: raise HTTPException(422, 'Escreva o que precisa ser combinado com o cliente.') with db.connect() as c: row = c.execute('''UPDATE dtf_local.orders SET contact_since=CASE WHEN %s THEN now() END, contact_by=CASE WHEN %s THEN %s END, contact_note=CASE WHEN %s THEN %s END WHERE id=%s AND cancelled_at IS NULL RETURNING number''', (body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado.') # The wait's history, for the time figures that leave it out (D-38). c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,)) if body.waiting: c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,)) audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user) return {'ok': True} @router.post('/api/operator/orders/{uid}/proof') def proof_ok(uid: UUID, user=Depends(can('print'))): """The print room checked the proof: the order may reach Finalizado.""" with db.connect() as c: row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1 WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado.') audit('order_proof_ok', order=row['number'], operator=user) return {'ok': True, 'version': row['version']} class QueuePlace(StrictModel): """Where a dragged card lands: between two orders of its column, either of them absent at the top or the bottom.""" after: UUID | None = None before: UUID | None = None QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))' @router.post('/api/operator/orders/{uid}/queue') def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)): """An order's place in its column: by default its payment time; dragged, halfway between the orders it was dropped between. It neither changes the order's stage nor counts as activity (the stalled clock keeps running).""" 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() 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.') keys = {} for side in ('after', 'before'): other = getattr(body, side) if other: near = c.execute(f'SELECT state, {QUEUE_KEY} AS key FROM dtf_local.orders WHERE id=%s', (other,)).fetchone() if not near or near['state'] != row['state']: raise HTTPException(409, 'Os pedidos mudaram de etapa. Clique em Atualizar.') keys[side] = float(near['key']) if 'after' in keys and 'before' in keys: key = (keys['after'] + keys['before']) / 2 elif 'after' in keys: key = keys['after'] + 60 else: key = keys['before'] - 60 c.execute('UPDATE dtf_local.orders SET queue_key=%s WHERE id=%s', (key, uid)) audit('order_queue_moved', order=str(uid), operator=user) return {'ok': True, 'queue_key': key} @router.post('/api/operator/orders/{uid}/move') def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): if request.state.operator['role'] not in MOVERS: raise HTTPException(403, 'Seu perfil não permite esta ação.') with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') if body.version != row['version']: raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.') if row.get('cancelled_at'): raise HTTPException(409, 'Pedido cancelado.') if body.state == row['state']: return row back = BACK.get(row['state']) == body.state if body.state not in TRANSITIONS[row['state']] and not back: raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.") if not may_move(request.state.operator['role'], row['state'], body.state, back): raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.") if body.state == 'cor' and not body.reason.strip(): 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.') # 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 JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall() if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))): raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.') # Two at most per machine in Imprimindo (app/machines.py). if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)): raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']: 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)) changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone() # Entering the queue (Arte conferida) is Tiny's "Preparando envio"; # Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23). events = {'tra':'production_started','cor':'correction_needed','fin':'ready'} if body.state in events and not back and payments.in_tiny(row): # "Production started" and "ready" reach the customer once per order, # even if a mistaken move is undone and made again. Each correction # is a new request, so it keeps one message per movement. once = body.state in ('tra','fin') event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason, 'customer_path': f'/portal.html?order={uid}'} # Tiny needs the order (customer, pickup or delivery) and, once the # sale reached it, its id, to set the situação without a search. sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", (f'{uid}:paid:tiny',)).fetchone() tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')} key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny' enqueue(c, key, 'tiny', tiny) return changed @router.post('/api/operator/orders/{uid}/print-files') def regenerate(uid: UUID, user=Depends(can('produce'))): """Queue generation again for items that failed or went to manual preparation, and for orders paid before the generator existed.""" with db.connect() as c: row = c.execute('SELECT id,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') if row['state'] not in ('rec','tra'): raise HTTPException(409, 'Print files are generated only before the order is queued') if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone(): raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand') queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True) audit('print_file_requeued', order=str(uid), operator=user) return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall() @router.post('/api/operator/payment-events/{uid}/resolve') def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))): with db.connect() as c: row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''', (user, body.note, uid)).fetchone() if not row: raise HTTPException(404, 'No open payment issue with this id') audit('payment_issue_resolved', payment_event=str(uid), operator=user) return {'ok': True} def tiny_status(): if not tiny.configured(): return {'configured': False} return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny', **tiny.TinyAuth().status()} @router.post('/api/operator/tiny/connect') def tiny_connect(user=Depends(can('integrations'))): """Start the one-time authorisation of this system in the client's Tiny.""" if not tiny.configured(): raise HTTPException(503, 'Tiny application is not configured') audit('tiny_connect_started', operator=user) return {'url': tiny.TinyAuth().authorize_url(user)} @router.post('/api/operator/tiny/test') def tiny_test(user=Depends(can('integrations'))): """Read one order and one contact from Tiny. Creates nothing.""" if not tiny.configured(): raise HTTPException(503, 'Tiny application is not configured') try: results = tiny.check() except tiny.TinyNotConnected as exc: raise HTTPException(409, str(exc)) audit('tiny_tested', operator=user, ok=all(v == 'ok' for v in results.values())) return {'ok': all(v == 'ok' for v in results.values()), 'results': results} @router.post('/api/operator/mercadopago/check') def mercadopago_check(user=Depends(can('integrations'))): """The Mercado Pago account behind the configured token; reads only.""" if payment.name != 'mercadopago': raise HTTPException(409, 'Mercado Pago não está configurado') from ..mercadopago_probe import check audit('mercadopago_check', operator=user) result = check(payment.access_token) # Whether Mercado Pago's notifications reach this server and pass the # signature: every accepted one is recorded, a refused one is audited. with db.connect() as c: received = c.execute('''SELECT count(*) AS n, max(received_at) AS last FROM dtf_local.payment_events WHERE provider='mercadopago' AND received_at > now()-interval '24 hours' ''').fetchone() last = c.execute('''SELECT received_at,status,outcome FROM dtf_local.payment_events WHERE provider='mercadopago' ORDER BY received_at DESC LIMIT 1''').fetchone() refused = c.execute('''SELECT count(*) AS n FROM dtf_local.security_events WHERE event='payment_webhook_rejected' AND created_at > now()-interval '24 hours' ''').fetchone() result['webhooks'] = {'accepted_24h': received['n'], 'refused_24h': refused['n'], 'last': last} return result @router.get('/api/operator/tiny/callback') def tiny_callback(code: str = Query('', max_length=4096), state: str = Query('', max_length=128), error: str = Query('', max_length=128)): """Tiny's redirect back. Cross-site, so the operator cookie is absent: the single-use state an operator created is what authorises it. Tiny reports a refusal (the operator declined, or offline access is not allowed for this application) with `error` instead of a code.""" if not tiny.configured(): raise HTTPException(503, 'Tiny application is not configured') try: if error == 'invalid_scope': retry = tiny.TinyAuth().without_offline(state) audit('tiny_offline_refused') return RedirectResponse(retry, status_code=303) if error or not code: raise tiny.TinyError(f'Tiny returned {error or "no code"}') who = tiny.TinyAuth().complete(code, state) except tiny.TinyError: audit('tiny_connect_failed') return RedirectResponse('/?tiny=failed', status_code=303) audit('tiny_connected', operator=who) return RedirectResponse('/?tiny=connected', status_code=303) @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'}) # Real work only: an operator's test order and a cancelled one are not production. REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'" # Where orders come from (D-21), in the order Números lists them. ORIGINS = ('site', 'dropflow', 'atendimento') LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" def waited(order, start, end): """SQL: the seconds `order` spent in "Aguardando contato" between `start` and `end`. Dropstar's rule D-38: that wait has no deadline and does not count in the time figures.""" return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now())) - greatest({start}, w.started_at))) FROM dtf_local.contact_waits w WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)''' # Longest period one request may cover: a year and a day, for a year against the last. STATS_MAX_DAYS = 366 def stats_period(days, start, end): """The local days a request covers: the last `days`, or start to end.""" today = datetime.now(timezone(timedelta(hours=-3))).date() if start is None and end is None: days = days or 30 return today - timedelta(days=days - 1), today if start is None or end is None: raise HTTPException(422, 'Informe a data inicial e a final.') if start > end: raise HTTPException(422, 'A data inicial é depois da final.') if (end - start).days + 1 > STATS_MAX_DAYS: raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.') return start, end @router.get('/api/operator/stats') def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None, end: date | None = None, user=Depends(operator)): """Production numbers from what the board already records: orders paid in the period, how long each stage holds an order, what each machine printed, and what is waiting now. The period is the last `days`, or start to end.""" start, end = stats_period(days, start, end) period = (start, end) within = f"{LOCAL_DAY} BETWEEN %s AND %s" metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)" with db.connect() as c: total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='cor' AND NOT m.back)) AS corrected FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone() daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders, COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} GROUP BY 1''', period).fetchall()} # Each order's stages as spans: from entering a stage to the next move. spans = f'''WITH events AS ( SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} UNION ALL SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {within}) SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events''' # Orders, not passages: an order sent back counts once, its passages apart, # and its time in a stage is the sum of its passages. Otherwise an order # that came back twice reads as three quick passages, not one slow order. stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages, percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) / 3600 AS median_hours FROM (SELECT id, state, count(*) AS passages, sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) AS seconds FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order GROUP BY state''', period + period).fetchall() lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL WHERE {REAL_ORDER} AND {within}''', period).fetchone() # What waits now, however old, and since when in its stage. waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE( (SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state), o.created_at))) / 3600 AS oldest_hours FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall() printed = machine_output(c, start, end) # Rework of the period (D-02 to D-04): the authorized ones, by the day # they were opened, over the film the machines printed in it. not_test = "COALESCE(o.payment->>'provider','') <> 'teste'" opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s" redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres, count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()} # The house's rework enters the pay of who printed it (D-02). by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who, sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''', (CUSTOMER_CAUSE,) + period).fetchall() undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at, {person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall() # Arte tratada, for the designer's productivity: orders of the period # whose final someone prepared, by who approved it (any version). treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id LEFT JOIN dtf_local.operators op ON op.email=f.created_by WHERE {REAL_ORDER} AND {within} AND {TREATED} GROUP BY 1 ORDER BY 2 DESC, 1''', period).fetchall() treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''', period).fetchone()['n'] # Each way in apart (D-21): what came from where, and how long it took # from payment to Finalizado, Aguardando contato left out as above. origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON true WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()} series = [] for offset in range((end - start).days + 1): day = start + timedelta(days=offset) row = daily.get(day) series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0, 'metres': float(row['metres']) if row else 0.0}) hours = lambda value: round(float(value), 1) if value is not None else None return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(), 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']), 'corrected': total['corrected'], 'daily': series, 'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]}, 'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0, 'cents': int(origins[name]['cents']) if name in origins else 0, 'metres': float(origins[name]['metres']) if name in origins else 0.0, 'finished': origins[name]['finished'] if name in origins else 0, 'median_hours': hours(origins[name]['median_hours']) if name in origins else None} for name in ORIGINS], 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], 'median_hours': hours(row['median_hours'])} for row in stages}, 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, 'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)} def rework_figures(printed, redone, by_printer, undecided): """Números' rework: per cause, the metres redone over the film printed, against the goal; the house's total against four times it.""" film = Decimal(str(sum(m['metres'] for m in printed))) share = lambda metres: float(round(100 * metres / film, 2)) if film else None causes = [] for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,): row = redone.get(cause) metres = Decimal(row['metres']) if row else Decimal(0) causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0, 'percent': share(metres)}) house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE) return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT), 'house': {'metres': float(house), 'percent': share(house), 'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))}, 'causes': causes, 'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer], 'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'], 'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(), 'opened_by': row['opened_name']} for row in undecided]} def machine_output(c, start, end): """What each machine printed in the period: the orders that reached Finalizado then, on the machine they were on, their metres, the hours they spent in Imprimindo (so metres per hour is the machine's real pace, as the room moves the cards), when it last finished one, and what it has now. The metres are the film printed, not the metres billed: billing rounds up to 10 cm and to one metre at least, and a 0,40 m order printed as 1 m would make the machine look faster than it is. Orders in Imprimindo on the same machine at the same time share that time: it counts once.""" metres = ("(SELECT COALESCE(sum(COALESCE(i->>'metres', i->>'billed_metres')::numeric),0)" " FROM jsonb_array_elements(o.snapshot->'items') i)") done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at FROM dtf_local.orders o JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''', (start, end)).fetchall() ids = [row['id'] for row in done] printing = {} for row in c.execute('''WITH events AS ( SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m WHERE m.order_id=ANY(%s)), spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events) SELECT id, at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else []: printing.setdefault(row['id'], []).append((row['at'], row['until'])) last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin' WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()} result = [] for m in machines.rows(c): mine = [row for row in done if str(row['machine_id'] or '') == m['id']] hours_in = busy_hours([span for row in mine for span in printing.get(row['id'], [])]) made = float(sum(row['metres'] for row in mine)) result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine), 'metres': made, 'printing_hours': round(hours_in, 2), 'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None, 'last_finished': last[m['id']].isoformat() if m['id'] in last else None, 'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}}) loose = [row for row in done if row['machine_id'] is None] if loose: result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose), 'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None, 'metres_per_hour': None, 'last_finished': None, 'now': {}}) return result def busy_hours(spans): """The hours the spans (start, end) cover, time shared by several counted once.""" seconds, reached = 0.0, None for at, until in sorted(spans): if reached is None or at >= reached: seconds += (until - at).total_seconds() reached = until elif until > reached: seconds += (until - reached).total_seconds() reached = until return seconds / 3600 def named_files(rows): """Each file named after its order and item, so a folder of them stays readable, with a link straight to storage.""" files, names = [], set() for row in rows: prefix = file_prefix(row['number'], row['item_index']) # Generated before 2026-10-23, a file was called pedido-23-item-1. older = f"pedido-{row['number']}-item-{row['item_index'] + 1}" name = row['name'] if name.startswith(older): name = prefix + name[len(older):] elif not name.startswith(prefix): name = f"{prefix}-{name}" stem, dot, ext = name.rpartition('.') copy = 2 while name in names: name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})' copy += 1 names.add(name) files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'], 'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)}) return files def print_ready(c, request, 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.""" 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 FROM dtf_local.orders o JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK} UNION ALL SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) FROM dtf_local.orders o JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND f.active AND f.item_index=p.item_index) 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] @router.get('/api/operator/orders/{uid}/folder-files') def folder_files(uid: UUID, request: Request, 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])) 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'))): """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',))) # 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)) return {'files': files} class FolderSync(StrictModel): early: bool = False held: list[UUID] = Field(default_factory=list, max_length=1000) # When the folders were chosen: the orders paid since are fetched whatever # their stage, so what passed while the computer was off is not lost. since: datetime | None = None @router.post('/api/operator/queue/folder') def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))): """What the Kanban's automatic folders should hold. `early` is Dropstar's three 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 they print, are checked in Revisão and sit in Finalizado, so one taken out of a folder can be fetched again when the order moves on. With `since`, also every order paid after the folders were chosen, whatever its stage: a computer that was off catches up on what passed meanwhile (Dropstar's rules, 2026-10-26). Without it, only the queue's (Firefox's downloads). `states` answers for the orders the 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',)) if body.early and body.held: rows += print_ready(c, request, ('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) 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)', (body.held,)).fetchall() if body.held else [] return {'files': files, 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}} @router.get('/api/operator/uploads/{uid}/download') def download(uid: UUID, user=Depends(operator)): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone() if not row: raise HTTPException(404, 'Completed upload not found') if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Artwork retention expired') require_clean(row) return {'name':row['name'], 'url':storage.download(row['object_key'],row['name']), 'expires_in':300}