diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6adb633..0de0c2c 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -16,7 +16,7 @@ jobs: uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Run fast regression checks run: | - python3 -m py_compile app/*.py app/**/*.py ops/*.py deploy/*.py + python3 -m py_compile app/*.py app/*/*.py app/*/*/*.py ops/*.py deploy/*.py python3 -m unittest \ tests.test_dependency_lock \ tests.test_staging_readiness \ diff --git a/app/api/operator.py b/app/api/operator.py deleted file mode 100644 index 156d2b4..0000000 --- a/app/api/operator.py +++ /dev/null @@ -1,1920 +0,0 @@ -"""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, uuid4 - -from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response -from fastapi.responses import RedirectResponse -from pydantic import Field -from psycopg.types.json import Jsonb - -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 Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart -from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files -from .. import cnpj, hotfolder, machine_log, machines, mail, payments, proof, prumo, quote_review, receipt, reviews, unpaid -from .. import tiny -from ..payments import release_files -from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, - TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row) -from .uploads import begin_upload -from ..scanning import require_clean - -router = APIRouter() - -# A quote that can still become an order: waiting for review, or approved and -# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until -# then it stays, even past the payment window while an attempt is still live. -LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)" - -@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(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(), '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 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_parts 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_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']) - # A paid treatment gives Art received its extra hours to prepare the art. - treatment = (order.get('snapshot') or {}).get('treatment') or {} - if order['state'] == 'rec' and treatment: - limit_hours += float(treatment.get('hours', 24)) - 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/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('payments'))): - """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'] - for row in rows: - row.update(payment_context(c, row)) - return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])} - - -def payment_context(c, row): - """Who tried to pay and for what: the quote the payment points to (its - customer, items and total), its order if there is one, the method of the - last attempt and Mercado Pago's own words about the payment.""" - payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {} - out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None} - try: - quote_id = UUID(str(row.get('reference') or '')) - except ValueError: - return out - quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone() - if not quote: - return out - out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'], - 'total_cents': (quote['approved'] or {}).get('total_cents')} - out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone() - attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s - ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone() - out['method'] = attempt['method'] if attempt else None - return out - - -@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_views(c, 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(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: - # Real orders: a proof card is found through its order (app/proof.py). - orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL - 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 = with_print_files(c, orders) - quotes = quote_views(c, 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 - UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''', - (uid, uid, uid)).fetchall()} - candidates = produced - originals if test else produced | originals - # Its proof cards (app/proof.py) go with it. - cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()] - for table in ('movements', 'order_files', 'print_files'): - c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,)) - 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} - - -@router.post('/api/operator/orders/{uid}/cancel') -def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))): - """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.') - hotfolder.stop(c, uid) - 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, request: Request, user=Depends(can('print'))): - """Exceptional manual choice before printing; the operator's pull is final.""" - if request.state.operator['role'] == 'operador': - raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.') - with db.connect() as c: - current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() - if not current: - raise HTTPException(404, 'Pedido não encontrado.') - proof.require_unlocked(c, current) - if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'): - raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.') - if body.machine_id: - target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone() - if not target or not target['active']: - raise HTTPException(404, 'Máquina não encontrada ou desativada.') - if machines.product_family(current) not in target['products']: - raise HTTPException(409, f"A {target['name']} não imprime este produto.") - linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders - WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() - if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']: - raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.') - 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 current['parent_id']: - c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', - (body.machine_id, body.machine_id is not None, current['parent_id'])) - elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'): - c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', - (body.machine_id, body.machine_id is not None, linked['id'])) - audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user) - return {'ok': True} - - -@router.post('/api/operator/orders/{uid}/contraction') -def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))): - """The contraction class of an item (Dropstar, 2026-10-30): the browser's - measure comes prefilled, and whoever prepares the art may change it until - the order prints. Both stay: the measure in the snapshot, the choice here.""" - with db.connect() as c: - row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE', - (uid,)).fetchone() - if not row: - raise HTTPException(404, 'Pedido não encontrado.') - proof.require_unlocked(c, row) - if body.item_index >= len(row['snapshot']['items']): - raise HTTPException(422, 'Item não encontrado no pedido.') - # Printing, the class still changes while the item's files wait to go - # into the hot folder: the class is its folder (item 10). - written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s - AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone() - if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written: - raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.') - chosen = dict(row['contraction'] or {}) - key = str(body.item_index) - if body.value is None: - chosen.pop(key, None) - else: - chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()} - c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid)) - audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user) - return {'ok': True, 'contraction': chosen} - - -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} - - -class ProofAnswer(StrictModel): - result: Literal['ok', 'rejected'] - reason: str = Field(default='', max_length=500) - - -@router.post('/api/operator/orders/{uid}/proof-answer') -def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))): - """The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK - puts its order in the queue; Prova reprovada, with its reason, sends the - order back to Arte recebida. Either way the card closes.""" - reason = ' '.join(body.reason.split()) - if body.result == 'rejected' and len(reason) < 3: - raise HTTPException(422, 'Diga por que a prova foi reprovada.') - with db.connect() as c: - card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() - if not card or not card.get('parent_id'): - raise HTTPException(404, 'Card de prova não encontrado.') - if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev': - raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.') - parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone() - c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s, - proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''', - (body.result, user, reason or None, uid)) - label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) - VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label)) - if body.result == 'ok': - # A prova aprovada é a conferência do pai: os arquivos completos - # que o Prumo gerou entram como finais, e o pai segue para a fila. - # Itens que ainda dependem de preparo manual continuam em Arte - # recebida, com o botão de final disponível. - if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'): - generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p - WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f - WHERE f.order_id=p.order_id AND f.item_index=p.item_index - AND f.kind='final' AND f.active) - ORDER BY p.item_index''', (parent['id'],)).fetchall() - for row in generated: - c.execute('''INSERT INTO dtf_local.order_files - (id,order_id,upload_id,item_index,kind,note,created_by) - VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''', - (uuid4(), parent['id'], row['upload_id'], row['item_index'], - f'Aprovado pela prova do #{card["number"]}')) - treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else '' - ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f - JOIN dtf_local.orders o ON o.id=f.order_id - JOIN dtf_local.uploads u ON u.id=f.upload_id - WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} - {treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone() - for i in range(len(parent['snapshot']['items']))) - c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(), - state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id'])) - if ready: - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) - VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user)) - elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']: - # Back to Arte recebida with the reason; its final is approved again. - c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],)) - c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL, - machine_id=NULL,machine_chosen=false, - version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],)) - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) - VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label)) - # The proof answer is the contact with the customer: the old - # "Aguardando contato" mark has done its job either way (0.1). - c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL - WHERE id=%s''', (parent['id'],)) - c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', - (parent['id'],)) - audit('order_proof_answered', order=parent['number'], result=body.result, operator=user) - return {'ok': True} - - -@router.post('/api/operator/orders/{uid}/proof-card') -def new_proof_card(uid: UUID, user=Depends(can('produce'))): - """A new proof card for an order whose proof was rejected, or that has - none yet (an order from before the cards).""" - with db.connect() as c: - row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() - if not row or row.get('parent_id'): - raise HTTPException(404, 'Pedido não encontrado.') - if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid): - raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.') - child = proof.create_child(c, row) - if not child: - raise HTTPException(409, 'Este pedido não leva prova.') - audit('order_proof_card', order=row['number'], operator=user) - return {'ok': True, 'id': child['id'], 'number': child['number']} - - -@router.post('/api/operator/orders/{uid}/proof') -def proof_ok(uid: UUID, user=Depends(can('print'))): - """An order from before the proof cards: the print room checked the - proof, and the order may reach Finalizado.""" - with db.connect() as c: - if proof.open_child(c, uid): - raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.') - 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']} - - -def paid_with(c, order): - """How the order was paid, for its receipt: pix, card, cash, credit, or - 'teste' for an operator's test order.""" - paid = order.get('payment') or {} - if paid.get('provider') == 'teste': - return 'teste' - if paid.get('provider') == payments.MANUAL_PROVIDER: - return paid.get('method') - row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' - ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone() - return row and row['method'] - - -@router.get('/api/operator/orders/{uid}/receipt') -def pickup_receipt(uid: UUID, user=Depends(operator)): - """The pickup receipt's PDF (item 14), for the folder to save or someone - to print again.""" - with db.connect() as c: - order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() - if not order: - raise HTTPException(404, 'Pedido não encontrado.') - if not receipt.is_pickup(order['snapshot']): - raise HTTPException(409, 'Só pedido de retirada tem recibo.') - body = receipt.render(order, paid_with(c, order)) - return Response(body, media_type='application/pdf', - headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'}) - - -@router.post('/api/operator/orders/{uid}/receipt/claim') -def claim_receipt(uid: UUID, user=Depends(can('print'))): - """One computer's folder takes the receipt to save: once, so the counter's - queue never prints it twice.""" - with db.connect() as c: - row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s - WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL - RETURNING number''', (user, uid)).fetchone() - if not row: - raise HTTPException(409, 'Este recibo já foi salvo.') - audit('pickup_receipt_saved', order=row['number'], operator=user) - return {'ok': True} - - -@router.post('/api/operator/orders/{uid}/receipt/release') -def release_receipt(uid: UUID, user=Depends(can('print'))): - """The folder could not save the receipt it took: another computer may.""" - with db.connect() as c: - c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL - WHERE id=%s AND receipt_saved_by=%s''', (uid, user)) - return {'ok': True} - - -def pickup_order(c, uid, lock=False): - """An order in Finalizado to be picked up, or why it cannot be marked.""" - order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone() - if not order: - raise HTTPException(404, 'Pedido não encontrado.') - if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']): - raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.') - if order['picked_up_at']: - raise HTTPException(409, 'Este pedido já foi marcado como retirado.') - return order - - -@router.post('/api/operator/orders/{uid}/pickup-uploads') -def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))): - """The photo of the signed receipt, sent before marking the order.""" - with db.connect() as c: - pickup_order(c, uid) - return begin_upload(body, session_id=operator_identity(user)) - - -class PickedUp(StrictModel): - photo: UUID | None = None - - -PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif') - - -@router.post('/api/operator/orders/{uid}/picked-up') -def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))): - """"Retirado": when and who handed the order over, and the photo of the - signed receipt when there is one (item 14). Finalizado means ready; this - closes the cycle. The photo is kept 30 days, as the order's files are.""" - with db.connect() as c: - order = pickup_order(c, uid, lock=True) - if body.photo: - photo = upload_row(c, body.photo, operator_identity(user), lock=True) - if not photo['complete']: - raise HTTPException(409, 'Espere a foto terminar de enviar.') - if not photo['name'].lower().endswith(PHOTO_TYPES): - raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).') - require_clean(photo) - c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,)) - row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s - WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone() - audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo)) - return {'ok': True, 'picked_up_at': row['picked_up_at']} - - -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 id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() - if not row: - raise HTTPException(404, 'Order not found') - proof.require_unlocked(c, row) - if not may_reorder(request.state.operator['role'], row['state']): - raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.') - mine = request.state.operator['machine'] - if (request.state.operator['role'] == 'operador' and row['state'] != 'tra' - and (not mine or str(row['machine_id'] or '') != mine['id'])): - raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.') - 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.') - proof.require_unlocked(c, row) - 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.') - # The machine of this session takes a card when it is pulled. A proof - # and its parent must keep the same physical machine. - account = request.state.operator - session_machine = account['machine'] - pulling = row['state'] == 'tra' and body.state == 'imp' - if account['role'] == 'operador': - if not session_machine: - raise HTTPException(409, 'Escolha a máquina em que você está.') - if not pulling and str(row['machine_id'] or '') != session_machine['id']: - raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.') - if pulling: - chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id']) - if not chosen: - raise HTTPException(409, 'Escolha a máquina que está puxando este card.') - if account['role'] == 'operador' and str(chosen) != session_machine['id']: - raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.") - target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone() - if not target or not target['active']: - raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.') - if machines.product_family(row) not in target['products']: - raise HTTPException(409, f"A {target['name']} não imprime este produto.") - # The machine's sheet speaks between one file and the next, never in - # the middle: a blocking alert stops this card here (app/machine_log.py). - blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']] - if blocking: - raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text']) - linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s - AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() - if linked and linked['machine_id'] and chosen != linked['machine_id']: - raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.') - row['machine_id'] = chosen - c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid)) - if row['parent_id']: - c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', - (chosen, row['parent_id'])) - # 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.') - if row['snapshot'].get('treatment') and not row['parent_id']: - treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f - JOIN dtf_local.orders o ON o.id=f.order_id - JOIN dtf_local.uploads u ON u.id=f.upload_id - WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall() - if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))): - raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.') - # 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.') - # A proof card ends with its answer, not in Finalizado; its order waits - # for that answer outside the queue (app/proof.py). - if row.get('parent_id') and body.state == 'fin': - raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.') - if body.state == 'imp' and proof.waiting(c, row): - raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.') - if body.state == 'fin' and not row.get('parent_id') 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.') - # Above 1 m the review photo is the evidence the sheet was checked; a - # proof card is no sale and skips this (app/reviews.py). - if (body.state == 'fin' and not back and not row.get('parent_id') - and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)): - raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão 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,)) - # Who moved it, and on which machine: the one it goes to print on, or - # else the mover's. - machine_name = (session_machine or {}).get('name') - if body.state == 'imp' and row['machine_id']: - machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', - (row['machine_id'],)).fetchone() or {}).get('name') - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine) - VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name)) - # Pulled to Imprimindo, its files go to its machine's hot folder; out - # of it, what Flexi did not take leaves (item 10). - if row['state'] == 'imp': - hotfolder.stop(c, uid) - if body.state == 'imp': - hotfolder.start(c, uid) - # A pickup reaching Finalizado has its receipt due (item 14), once. - due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot']) - changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), - queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END, - receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END - WHERE id=%s RETURNING *''', (body.state, body.state, due, 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,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() - if not row: - raise HTTPException(404, 'Order not found') - proof.require_unlocked(c, row) - 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') - if row['parent_id']: - manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'", - (uid,)).fetchall() - for stuck in manual: - original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index'] - prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s - AND item_index=%s AND kind='final' AND active LIMIT 1''', - (row['parent_id'], original_index)).fetchone() - if not prepared: - raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.') - 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. -# A proof card (app/proof.py) is no sale either. -REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL" -# 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: - limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall() - limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} - for row in limit_rows} - 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() - # Approved quotes of the period nobody paid (front 9). - unpaid_figures = unpaid.figures(c, start, end) - 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, - avg(seconds) / 3600 AS average_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() - # Passages past each stage's acceptable time (front 11), in the - # selected period and today. - # Each passage carries whether its order paid for treatment, which only - # Art received counts (front 5). - late_rows = c.execute(f'''SELECT s.state, - extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds, - (s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day, - o.snapshot->'treatment' AS treatment - FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''', - period + period).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()} - # Coupons used by the period's paid orders (front 8.3): what each code - # brought in orders, billed metres, discount and money received. - coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id, - o.snapshot->'coupon'->>'code' AS code, count(*) AS orders, - COALESCE(sum({metres}),0) AS metres, - COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents, - COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents - FROM dtf_local.orders o - WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL - GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall() - # Speed (item 0.12): the browser's marks on the way to a quote, the - # Prumo's print generation and the time from payment event to card. - site_speed = c.execute(f'''WITH samples AS ( - SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms, - (o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms, - (o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes, - (o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms, - (o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms - FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}) - SELECT - avg(page_ms) AS page_avg, - percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n, - avg((upload_ms/1000.0)/(upload_bytes/1048576.0)) - FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg, - percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_ms/1000.0)/(upload_bytes/1048576.0)) - FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95, - count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n, - avg(analysis_ms) AS analysis_avg, - percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n, - avg(montage_ms) AS montage_avg, - percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n - FROM samples''', period).fetchone() - print_speed = c.execute(f'''WITH samples AS ( - SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds, - COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric, - (o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres - FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id - WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL - AND p.item_index < jsonb_array_length(o.snapshot->'items')) - SELECT avg(seconds) AS avg_s, - percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n, - avg(seconds/NULLIF(metres/10,0)) - FILTER (WHERE metres>0) AS per10_avg, - percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0)) - FILTER (WHERE metres>0) AS per10_p95, - count(*) FILTER (WHERE metres>0) AS per10_n - FROM samples''', period).fetchone() - card_speed = c.execute(f'''WITH samples AS ( - SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds - FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text - WHERE {REAL_ORDER} AND {within} GROUP BY o.id) - SELECT avg(seconds) AS avg_s, - percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n - FROM samples WHERE seconds >= 0''', period).fetchone() - today = datetime.now(timezone(timedelta(hours=-3))).date() - late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')} - for row in late_rows: - limit = limits.get(row['state']) - if not limit: - continue - hours = float(limit['hours']) - treatment = row.get('treatment') or {} - if row['state'] == 'rec' and treatment: - hours += float(treatment.get('hours', 24)) - if row['seconds'] > hours * 3600: - late[row['state']]['count'] += 1 - if row['day'] == today: - late[row['state']]['today'] += 1 - 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], - 'unpaid': unpaid_figures, - 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, - 'stage_limits': limits, 'late': late, - 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], - 'average_hours': hours(row['average_hours'])} for row in stages}, - 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, - 'speed': speed_figures(site_speed, print_speed, card_speed), - 'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided), - 'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'], - 'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']), - 'cents': int(row['cents'])} for row in coupons_used]} - - -def speed_figures(site, generation, card): - """Números' speed block: average and slow-case p95, in seconds per unit.""" - def pair(avg, p95, n, scale=1): - return {'average': round(float(avg)/scale, 2) if avg is not None else None, - 'p95': round(float(p95)/scale, 2) if p95 is not None else None, - 'samples': int(n or 0)} - return [ - {'key': 'page', 'label': 'Abrir o montador', 'unit': 's', - **pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)}, - {'key': 'upload', 'label': 'Subir o arquivo', 'unit': 's/MB', - **pair(site['upload_avg'], site['upload_p95'], site['upload_n'])}, - {'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's', - **pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)}, - {'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's', - **pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)}, - {'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's', - **pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])}, - {'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's', - **pair(card['avg_s'], card['p95_s'], card['n'])}, - ] - - -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, 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.""" - 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,pp.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.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index - JOIN dtf_local.uploads u ON u.id=pp.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,name''', - (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() - return rows - - -@router.get('/api/operator/orders/{uid}/view') -def view_files(uid: UUID, user=Depends(operator)): - """What "Abrir e conferir" shows (item 7): each item's generated PNG, part - by part, with links to its pieces, then the customer's originals, which - have only their picture.""" - with db.connect() as c: - order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() - if not order: - raise HTTPException(404, 'Pedido não encontrado.') - made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready' - ORDER BY item_index''', (uid,)).fetchall() - parts = c.execute('''SELECT 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=%s AND u.purged_at IS NULL - ORDER BY p.item_index, p.part''', (uid,)).fetchall() - pictured = {str(r['upload_id']) for r in c.execute( - 'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', - ([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()} - items = order['snapshot']['items'] - many = len(items) > 1 - files = [] - for row in made: - mine = [p for p in parts if p['item_index'] == row['item_index']] - details = {d.get('name'): d for d in row['detail'].get('parts') or []} - for part in mine: - tiles = (details.get(part['name']) or {}).get('tiles') - label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \ - (f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '') - files.append({'name': part['name'], 'label': label, 'item': row['item_index'], - 'manifest': tiles and {**tiles, 'urls': [ - [storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png') - for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}}) - for index, item in enumerate(items): - for n, upload in enumerate(item['uploads']): - files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original', - 'label': (f'Item {index + 1} · ' if many else '') + 'original' + - (f' {n + 1}' if len(item['uploads']) > 1 else ''), - 'item': index, 'manifest': None, - 'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None}) - return {'files': files} - - -@router.get('/api/operator/orders/{uid}/folder-files') -def folder_files(uid: UUID, 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, (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(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, ('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/hot') -def queue_hot(user=Depends(can('print'))): - """For a computer with the automatic folders: the parts it should write - into the machines' hot folders now, claimed for it alone; those written - and not yet taken by Flexi, to see whether they still are; and those to - delete, withdrawn from cards that left Imprimindo (item 10).""" - with db.connect() as c: - due = hotfolder.claim(c, user) - keys = {str(r['upload_id']): r['object_key'] for r in c.execute( - 'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)', - ([r['upload_id'] for r in due],)).fetchall()} if due else {} - watched = hotfolder.watched(c) - return {'folder': hotfolder.PRINTING_FOLDER, - 'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'], - 'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due], - 'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} - for r in watched if r['state'] == 'written'], - 'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} - for r in watched if r['state'] == 'withdraw']} - - -class HotReport(StrictModel): - state: Literal['written', 'released', 'consumed', 'gone'] - - -@router.post('/api/operator/queue/hot/{part_id}') -def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))): - """What a computer saw of a part: written, not written, taken by Flexi, - or deleted after it was withdrawn.""" - with db.connect() as c: - applied = hotfolder.report(c, part_id, body.state, user) - if applied and body.state == 'written': - audit('hot_folder_written', part=part_id, operator=user) - return {'ok': applied} - - -@router.post('/api/operator/queue/folder') -def queue_folder(body: FolderSync, user=Depends(can('print'))): - """What the Kanban's automatic folders should hold. `early` is Dropstar's - stage 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, ('rec', 'tra') if body.early else ('tra',)) - if body.early and body.held: - rows += print_ready(c, ('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, ('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 [] - # The pickup receipts no computer saved yet (item 14), due since the - # folders were chosen: one that was off catches up, like the files. - due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL - AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s) - ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else [] - # The review photos and videos to copy into Revisões/ (front 2). Without - # `since`, the last 30 days, so a new computer catches up. - since = body.since or datetime.now(timezone.utc) - timedelta(days=30) - review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name - FROM dtf_local.order_reviews r - JOIN dtf_local.orders o ON o.id=r.order_id - JOIN dtf_local.uploads u ON u.id=r.upload_id - WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall() - return {'files': files, - 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}, - 'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due], - 'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'], - 'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]} - - -@router.get('/api/operator/uploads/{uid}/download') -def download(uid: UUID, order_id: UUID | None = None, 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) - name = row['name'] - if order_id: - order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone() - if not order: - raise HTTPException(404, 'Pedido não encontrado.') - originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']] - if str(uid) not in originals: - raise HTTPException(422, 'Este arquivo não é original do pedido.') - index = originals.index(str(uid)) + 1 - suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin' - name = f'DTF-{order["number"]}-original-{index}.{suffix}' - return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300} diff --git a/app/api/operator/__init__.py b/app/api/operator/__init__.py new file mode 100644 index 0000000..4fa08be --- /dev/null +++ b/app/api/operator/__init__.py @@ -0,0 +1,17 @@ +"""Kanban: sign-in, the board, commercial review and card movement, by area. + +Each module owns its routes; this package keeps the single `router` app/app.py +includes and the names other modules imported from the old single file. +""" +from fastapi import APIRouter + +from . import board, common, files, integrations, orders, quotes, rework, session, stats +from .integrations import tiny_callback +from .stats import speed_figures + +router = APIRouter() +# The order the routes first appeared in the old file. Static paths that could +# meet a parameterised one stay ahead of it: /orders/finished before any +# /orders/{uid} GET. +for module in (common, session, integrations, board, quotes, rework, orders, stats, files): + router.include_router(module.router) diff --git a/app/api/operator/board.py b/app/api/operator/board.py new file mode 100644 index 0000000..8494686 --- /dev/null +++ b/app/api/operator/board.py @@ -0,0 +1,274 @@ +"""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 ...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(), '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']) + # A paid treatment gives Art received its extra hours to prepare the art. + treatment = (order.get('snapshot') or {}).get('treatment') or {} + if order['state'] == 'rec' and treatment: + limit_hours += float(treatment.get('hours', 24)) + 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'}) diff --git a/app/api/operator/common.py b/app/api/operator/common.py new file mode 100644 index 0000000..3ff55e0 --- /dev/null +++ b/app/api/operator/common.py @@ -0,0 +1,104 @@ +"""Helpers and constants shared by more than one Kanban router.""" +import re + +from fastapi import APIRouter, HTTPException + +from ... import cnpj +from ...core import db + +router = APIRouter() + +# A quote that can still become an order: waiting for review, or approved and +# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until +# then it stays, even past the payment window while an attempt is still live. +LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)" + +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_parts 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 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 + + +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 + + +# Real work only: an operator's test order and a cancelled one are not production. +# A proof card (app/proof.py) is no sale either. +REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL" +# Where orders come from (D-21), in the order Números lists them. +ORIGINS = ('site', 'dropflow', 'atendimento') diff --git a/app/api/operator/files.py b/app/api/operator/files.py new file mode 100644 index 0000000..b2562a7 --- /dev/null +++ b/app/api/operator/files.py @@ -0,0 +1,249 @@ +"""The print room's files: queue, folders, downloads and the order viewer.""" +from datetime import datetime, timedelta, timezone +from typing import Literal +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import Field + +from ... import hotfolder, receipt +from ...core import db +from ...core.auth import audit, can, operator +from ...core.models import StrictModel +from ...printjobs import file_prefix +from ...runtime import storage +from ...scanning import require_clean +from .common import FINAL_OK + +router = APIRouter() + +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, 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.""" + 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,pp.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.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index + JOIN dtf_local.uploads u ON u.id=pp.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,name''', + (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() + return rows + + +@router.get('/api/operator/orders/{uid}/view') +def view_files(uid: UUID, user=Depends(operator)): + """What "Abrir e conferir" shows (item 7): each item's generated PNG, part + by part, with links to its pieces, then the customer's originals, which + have only their picture.""" + with db.connect() as c: + order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready' + ORDER BY item_index''', (uid,)).fetchall() + parts = c.execute('''SELECT 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=%s AND u.purged_at IS NULL + ORDER BY p.item_index, p.part''', (uid,)).fetchall() + pictured = {str(r['upload_id']) for r in c.execute( + 'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', + ([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()} + items = order['snapshot']['items'] + many = len(items) > 1 + files = [] + for row in made: + mine = [p for p in parts if p['item_index'] == row['item_index']] + details = {d.get('name'): d for d in row['detail'].get('parts') or []} + for part in mine: + tiles = (details.get(part['name']) or {}).get('tiles') + label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \ + (f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '') + files.append({'name': part['name'], 'label': label, 'item': row['item_index'], + 'manifest': tiles and {**tiles, 'urls': [ + [storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png') + for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}}) + for index, item in enumerate(items): + for n, upload in enumerate(item['uploads']): + files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original', + 'label': (f'Item {index + 1} · ' if many else '') + 'original' + + (f' {n + 1}' if len(item['uploads']) > 1 else ''), + 'item': index, 'manifest': None, + 'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None}) + return {'files': files} + + +@router.get('/api/operator/orders/{uid}/folder-files') +def folder_files(uid: UUID, 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, (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(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, ('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/hot') +def queue_hot(user=Depends(can('print'))): + """For a computer with the automatic folders: the parts it should write + into the machines' hot folders now, claimed for it alone; those written + and not yet taken by Flexi, to see whether they still are; and those to + delete, withdrawn from cards that left Imprimindo (item 10).""" + with db.connect() as c: + due = hotfolder.claim(c, user) + keys = {str(r['upload_id']): r['object_key'] for r in c.execute( + 'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)', + ([r['upload_id'] for r in due],)).fetchall()} if due else {} + watched = hotfolder.watched(c) + return {'folder': hotfolder.PRINTING_FOLDER, + 'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'], + 'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due], + 'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} + for r in watched if r['state'] == 'written'], + 'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} + for r in watched if r['state'] == 'withdraw']} + + +class HotReport(StrictModel): + state: Literal['written', 'released', 'consumed', 'gone'] + + +@router.post('/api/operator/queue/hot/{part_id}') +def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))): + """What a computer saw of a part: written, not written, taken by Flexi, + or deleted after it was withdrawn.""" + with db.connect() as c: + applied = hotfolder.report(c, part_id, body.state, user) + if applied and body.state == 'written': + audit('hot_folder_written', part=part_id, operator=user) + return {'ok': applied} + + +@router.post('/api/operator/queue/folder') +def queue_folder(body: FolderSync, user=Depends(can('print'))): + """What the Kanban's automatic folders should hold. `early` is Dropstar's + stage 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, ('rec', 'tra') if body.early else ('tra',)) + if body.early and body.held: + rows += print_ready(c, ('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, ('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 [] + # The pickup receipts no computer saved yet (item 14), due since the + # folders were chosen: one that was off catches up, like the files. + due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL + AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s) + ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else [] + # The review photos and videos to copy into Revisões/ (front 2). Without + # `since`, the last 30 days, so a new computer catches up. + since = body.since or datetime.now(timezone.utc) - timedelta(days=30) + review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name + FROM dtf_local.order_reviews r + JOIN dtf_local.orders o ON o.id=r.order_id + JOIN dtf_local.uploads u ON u.id=r.upload_id + WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall() + return {'files': files, + 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}, + 'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due], + 'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'], + 'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]} + + +@router.get('/api/operator/uploads/{uid}/download') +def download(uid: UUID, order_id: UUID | None = None, 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) + name = row['name'] + if order_id: + order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']] + if str(uid) not in originals: + raise HTTPException(422, 'Este arquivo não é original do pedido.') + index = originals.index(str(uid)) + 1 + suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin' + name = f'DTF-{order["number"]}-original-{index}.{suffix}' + return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300} diff --git a/app/api/operator/integrations.py b/app/api/operator/integrations.py new file mode 100644 index 0000000..af9e600 --- /dev/null +++ b/app/api/operator/integrations.py @@ -0,0 +1,198 @@ +"""Integrations: freight, backup, payment events, Tiny and Mercado Pago.""" +import os +from datetime import datetime, timezone +from typing import Literal +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi.responses import RedirectResponse + +from ... import tiny +from ...core import db +from ...core.auth import audit, can +from ...core.models import Resolution +from ...runtime import freight, payment +from .common import thumbnails + +router = APIRouter() + +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/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('payments'))): + """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'] + for row in rows: + row.update(payment_context(c, row)) + return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])} + + +def payment_context(c, row): + """Who tried to pay and for what: the quote the payment points to (its + customer, items and total), its order if there is one, the method of the + last attempt and Mercado Pago's own words about the payment.""" + payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {} + out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None} + try: + quote_id = UUID(str(row.get('reference') or '')) + except ValueError: + return out + quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone() + if not quote: + return out + out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'], + 'total_cents': (quote['approved'] or {}).get('total_cents')} + out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone() + attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s + ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone() + out['method'] = attempt['method'] if attempt else None + return out + + +@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} + +@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) diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py new file mode 100644 index 0000000..caf08ac --- /dev/null +++ b/app/api/operator/orders.py @@ -0,0 +1,587 @@ +"""Order actions: cancel and delete, machine, contraction, contact, proof, +receipt and pickup, queue place, move, print-file regeneration.""" +from datetime import datetime, timezone +from typing import Literal +from uuid import UUID, uuid4 + +from fastapi import APIRouter, Depends, HTTPException, Request, Response +from pydantic import Field +from psycopg.types.json import Jsonb + +from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews +from ...core import db +from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator +from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart +from ...payments import release_files +from ...printjobs import queue as queue_print_files +from ...runtime import BACK, STATES, TRANSITIONS, enqueue, operator_identity, upload_row +from ...scanning import require_clean +from ..uploads import begin_upload +from .common import FINAL_OK, TREATED + +router = APIRouter() + +@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 + UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''', + (uid, uid, uid)).fetchall()} + candidates = produced - originals if test else produced | originals + # Its proof cards (app/proof.py) go with it. + cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()] + for table in ('movements', 'order_files', 'print_files'): + c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,)) + 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} + + +@router.post('/api/operator/orders/{uid}/cancel') +def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))): + """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.') + hotfolder.stop(c, uid) + 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, request: Request, user=Depends(can('print'))): + """Exceptional manual choice before printing; the operator's pull is final.""" + if request.state.operator['role'] == 'operador': + raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.') + with db.connect() as c: + current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not current: + raise HTTPException(404, 'Pedido não encontrado.') + proof.require_unlocked(c, current) + if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'): + raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.') + if body.machine_id: + target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone() + if not target or not target['active']: + raise HTTPException(404, 'Máquina não encontrada ou desativada.') + if machines.product_family(current) not in target['products']: + raise HTTPException(409, f"A {target['name']} não imprime este produto.") + linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders + WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() + if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']: + raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.') + 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 current['parent_id']: + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', + (body.machine_id, body.machine_id is not None, current['parent_id'])) + elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'): + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', + (body.machine_id, body.machine_id is not None, linked['id'])) + audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user) + return {'ok': True} + + +@router.post('/api/operator/orders/{uid}/contraction') +def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))): + """The contraction class of an item (Dropstar, 2026-10-30): the browser's + measure comes prefilled, and whoever prepares the art may change it until + the order prints. Both stay: the measure in the snapshot, the choice here.""" + with db.connect() as c: + row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE', + (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Pedido não encontrado.') + proof.require_unlocked(c, row) + if body.item_index >= len(row['snapshot']['items']): + raise HTTPException(422, 'Item não encontrado no pedido.') + # Printing, the class still changes while the item's files wait to go + # into the hot folder: the class is its folder (item 10). + written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s + AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone() + if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written: + raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.') + chosen = dict(row['contraction'] or {}) + key = str(body.item_index) + if body.value is None: + chosen.pop(key, None) + else: + chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()} + c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid)) + audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user) + return {'ok': True, 'contraction': chosen} + + +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} + + +class ProofAnswer(StrictModel): + result: Literal['ok', 'rejected'] + reason: str = Field(default='', max_length=500) + + +@router.post('/api/operator/orders/{uid}/proof-answer') +def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))): + """The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK + puts its order in the queue; Prova reprovada, with its reason, sends the + order back to Arte recebida. Either way the card closes.""" + reason = ' '.join(body.reason.split()) + if body.result == 'rejected' and len(reason) < 3: + raise HTTPException(422, 'Diga por que a prova foi reprovada.') + with db.connect() as c: + card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not card or not card.get('parent_id'): + raise HTTPException(404, 'Card de prova não encontrado.') + if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev': + raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.') + parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone() + c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s, + proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''', + (body.result, user, reason or None, uid)) + label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label)) + if body.result == 'ok': + # A prova aprovada é a conferência do pai: os arquivos completos + # que o Prumo gerou entram como finais, e o pai segue para a fila. + # Itens que ainda dependem de preparo manual continuam em Arte + # recebida, com o botão de final disponível. + if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'): + generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p + WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f + WHERE f.order_id=p.order_id AND f.item_index=p.item_index + AND f.kind='final' AND f.active) + ORDER BY p.item_index''', (parent['id'],)).fetchall() + for row in generated: + c.execute('''INSERT INTO dtf_local.order_files + (id,order_id,upload_id,item_index,kind,note,created_by) + VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''', + (uuid4(), parent['id'], row['upload_id'], row['item_index'], + f'Aprovado pela prova do #{card["number"]}')) + treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else '' + ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f + JOIN dtf_local.orders o ON o.id=f.order_id + JOIN dtf_local.uploads u ON u.id=f.upload_id + WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} + {treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone() + for i in range(len(parent['snapshot']['items']))) + c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(), + state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id'])) + if ready: + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user)) + elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']: + # Back to Arte recebida with the reason; its final is approved again. + c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],)) + c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL, + machine_id=NULL,machine_chosen=false, + version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],)) + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) + VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label)) + # The proof answer is the contact with the customer: the old + # "Aguardando contato" mark has done its job either way (0.1). + c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL + WHERE id=%s''', (parent['id'],)) + c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', + (parent['id'],)) + audit('order_proof_answered', order=parent['number'], result=body.result, operator=user) + return {'ok': True} + + +@router.post('/api/operator/orders/{uid}/proof-card') +def new_proof_card(uid: UUID, user=Depends(can('produce'))): + """A new proof card for an order whose proof was rejected, or that has + none yet (an order from before the cards).""" + with db.connect() as c: + row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row or row.get('parent_id'): + raise HTTPException(404, 'Pedido não encontrado.') + if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid): + raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.') + child = proof.create_child(c, row) + if not child: + raise HTTPException(409, 'Este pedido não leva prova.') + audit('order_proof_card', order=row['number'], operator=user) + return {'ok': True, 'id': child['id'], 'number': child['number']} + + +@router.post('/api/operator/orders/{uid}/proof') +def proof_ok(uid: UUID, user=Depends(can('print'))): + """An order from before the proof cards: the print room checked the + proof, and the order may reach Finalizado.""" + with db.connect() as c: + if proof.open_child(c, uid): + raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.') + 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']} + + +def paid_with(c, order): + """How the order was paid, for its receipt: pix, card, cash, credit, or + 'teste' for an operator's test order.""" + paid = order.get('payment') or {} + if paid.get('provider') == 'teste': + return 'teste' + if paid.get('provider') == payments.MANUAL_PROVIDER: + return paid.get('method') + row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' + ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone() + return row and row['method'] + + +@router.get('/api/operator/orders/{uid}/receipt') +def pickup_receipt(uid: UUID, user=Depends(operator)): + """The pickup receipt's PDF (item 14), for the folder to save or someone + to print again.""" + with db.connect() as c: + order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + if not receipt.is_pickup(order['snapshot']): + raise HTTPException(409, 'Só pedido de retirada tem recibo.') + body = receipt.render(order, paid_with(c, order)) + return Response(body, media_type='application/pdf', + headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'}) + + +@router.post('/api/operator/orders/{uid}/receipt/claim') +def claim_receipt(uid: UUID, user=Depends(can('print'))): + """One computer's folder takes the receipt to save: once, so the counter's + queue never prints it twice.""" + with db.connect() as c: + row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s + WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL + RETURNING number''', (user, uid)).fetchone() + if not row: + raise HTTPException(409, 'Este recibo já foi salvo.') + audit('pickup_receipt_saved', order=row['number'], operator=user) + return {'ok': True} + + +@router.post('/api/operator/orders/{uid}/receipt/release') +def release_receipt(uid: UUID, user=Depends(can('print'))): + """The folder could not save the receipt it took: another computer may.""" + with db.connect() as c: + c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL + WHERE id=%s AND receipt_saved_by=%s''', (uid, user)) + return {'ok': True} + + +def pickup_order(c, uid, lock=False): + """An order in Finalizado to be picked up, or why it cannot be marked.""" + order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']): + raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.') + if order['picked_up_at']: + raise HTTPException(409, 'Este pedido já foi marcado como retirado.') + return order + + +@router.post('/api/operator/orders/{uid}/pickup-uploads') +def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))): + """The photo of the signed receipt, sent before marking the order.""" + with db.connect() as c: + pickup_order(c, uid) + return begin_upload(body, session_id=operator_identity(user)) + + +class PickedUp(StrictModel): + photo: UUID | None = None + + +PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif') + + +@router.post('/api/operator/orders/{uid}/picked-up') +def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))): + """"Retirado": when and who handed the order over, and the photo of the + signed receipt when there is one (item 14). Finalizado means ready; this + closes the cycle. The photo is kept 30 days, as the order's files are.""" + with db.connect() as c: + order = pickup_order(c, uid, lock=True) + if body.photo: + photo = upload_row(c, body.photo, operator_identity(user), lock=True) + if not photo['complete']: + raise HTTPException(409, 'Espere a foto terminar de enviar.') + if not photo['name'].lower().endswith(PHOTO_TYPES): + raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).') + require_clean(photo) + c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,)) + row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s + WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone() + audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo)) + return {'ok': True, 'picked_up_at': row['picked_up_at']} + + +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 id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Order not found') + proof.require_unlocked(c, row) + if not may_reorder(request.state.operator['role'], row['state']): + raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.') + mine = request.state.operator['machine'] + if (request.state.operator['role'] == 'operador' and row['state'] != 'tra' + and (not mine or str(row['machine_id'] or '') != mine['id'])): + raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.') + 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.') + proof.require_unlocked(c, row) + 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.') + # The machine of this session takes a card when it is pulled. A proof + # and its parent must keep the same physical machine. + account = request.state.operator + session_machine = account['machine'] + pulling = row['state'] == 'tra' and body.state == 'imp' + if account['role'] == 'operador': + if not session_machine: + raise HTTPException(409, 'Escolha a máquina em que você está.') + if not pulling and str(row['machine_id'] or '') != session_machine['id']: + raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.') + if pulling: + chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id']) + if not chosen: + raise HTTPException(409, 'Escolha a máquina que está puxando este card.') + if account['role'] == 'operador' and str(chosen) != session_machine['id']: + raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.") + target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone() + if not target or not target['active']: + raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.') + if machines.product_family(row) not in target['products']: + raise HTTPException(409, f"A {target['name']} não imprime este produto.") + # The machine's sheet speaks between one file and the next, never in + # the middle: a blocking alert stops this card here (app/machine_log.py). + blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']] + if blocking: + raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text']) + linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s + AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() + if linked and linked['machine_id'] and chosen != linked['machine_id']: + raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.') + row['machine_id'] = chosen + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid)) + if row['parent_id']: + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', + (chosen, row['parent_id'])) + # 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.') + if row['snapshot'].get('treatment') and not row['parent_id']: + treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f + JOIN dtf_local.orders o ON o.id=f.order_id + JOIN dtf_local.uploads u ON u.id=f.upload_id + WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall() + if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))): + raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.') + # 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.') + # A proof card ends with its answer, not in Finalizado; its order waits + # for that answer outside the queue (app/proof.py). + if row.get('parent_id') and body.state == 'fin': + raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.') + if body.state == 'imp' and proof.waiting(c, row): + raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.') + if body.state == 'fin' and not row.get('parent_id') 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.') + # Above 1 m the review photo is the evidence the sheet was checked; a + # proof card is no sale and skips this (app/reviews.py). + if (body.state == 'fin' and not back and not row.get('parent_id') + and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)): + raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão 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,)) + # Who moved it, and on which machine: the one it goes to print on, or + # else the mover's. + machine_name = (session_machine or {}).get('name') + if body.state == 'imp' and row['machine_id']: + machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', + (row['machine_id'],)).fetchone() or {}).get('name') + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine) + VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name)) + # Pulled to Imprimindo, its files go to its machine's hot folder; out + # of it, what Flexi did not take leaves (item 10). + if row['state'] == 'imp': + hotfolder.stop(c, uid) + if body.state == 'imp': + hotfolder.start(c, uid) + # A pickup reaching Finalizado has its receipt due (item 14), once. + due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot']) + changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), + queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END, + receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END + WHERE id=%s RETURNING *''', (body.state, body.state, due, 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,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Order not found') + proof.require_unlocked(c, row) + 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') + if row['parent_id']: + manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'", + (uid,)).fetchall() + for stuck in manual: + original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index'] + prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s + AND item_index=%s AND kind='final' AND active LIMIT 1''', + (row['parent_id'], original_index)).fetchone() + if not prepared: + raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.') + 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() diff --git a/app/api/operator/quotes.py b/app/api/operator/quotes.py new file mode 100644 index 0000000..6e5e2b5 --- /dev/null +++ b/app/api/operator/quotes.py @@ -0,0 +1,159 @@ +"""Quotes: review, search, test and outside-paid orders, discard.""" +import re +from datetime import datetime +from typing import Literal +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import Field + +from ... import payments, quote_review +from ...core import db +from ...core.auth import audit, can, operator +from ...core.models import Review, StrictModel +from ...runtime import quote_views +from .board import with_print_files +from .common import (LIVE_QUOTE, MODES, company_names, customer_match, like, numeric, + thumbnails) + +router = APIRouter() + +@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_views(c, 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(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: + # Real orders: a proof card is found through its order (app/proof.py). + orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL + 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 = with_print_files(c, orders) + quotes = quote_views(c, 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 + + +@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} diff --git a/app/api/operator/rework.py b/app/api/operator/rework.py new file mode 100644 index 0000000..f29b46f --- /dev/null +++ b/app/api/operator/rework.py @@ -0,0 +1,73 @@ +"""Rework: its causes, and opening and deciding one (D-02 to D-04).""" +from decimal import Decimal +from typing import Literal +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import Field + +from ...core import db +from ...core.auth import audit, can +from ...core.models import StrictModel + +router = APIRouter() + +# 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 diff --git a/app/api/operator/session.py b/app/api/operator/session.py new file mode 100644 index 0000000..853d4cf --- /dev/null +++ b/app/api/operator/session.py @@ -0,0 +1,49 @@ +"""Kanban sign-in and sign-out.""" +import hashlib +import secrets + +from fastapi import APIRouter, HTTPException, Request, Response + +from ...core import db +from ...core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, + login_failed, password_matches, throttle) +from ...core.models import OperatorLogin + +router = APIRouter() + +@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} diff --git a/app/api/operator/stats.py b/app/api/operator/stats.py new file mode 100644 index 0000000..01ed0fd --- /dev/null +++ b/app/api/operator/stats.py @@ -0,0 +1,340 @@ +"""Números: the production figures and the SQL helpers they share.""" +from datetime import date, datetime, timedelta, timezone +from decimal import Decimal + +from fastapi import APIRouter, Depends, HTTPException, Query + +from ... import machines, unpaid +from ...core import db +from ...core.auth import operator +from .common import ORIGINS, REAL_ORDER, TREATED, person +from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT + +router = APIRouter() + +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: + limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall() + limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} + for row in limit_rows} + 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() + # Approved quotes of the period nobody paid (front 9). + unpaid_figures = unpaid.figures(c, start, end) + 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, + avg(seconds) / 3600 AS average_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() + # Passages past each stage's acceptable time (front 11), in the + # selected period and today. + # Each passage carries whether its order paid for treatment, which only + # Art received counts (front 5). + late_rows = c.execute(f'''SELECT s.state, + extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds, + (s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day, + o.snapshot->'treatment' AS treatment + FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''', + period + period).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()} + # Coupons used by the period's paid orders (front 8.3): what each code + # brought in orders, billed metres, discount and money received. + coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id, + o.snapshot->'coupon'->>'code' AS code, count(*) AS orders, + COALESCE(sum({metres}),0) AS metres, + COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents, + COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents + FROM dtf_local.orders o + WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL + GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall() + # Speed (item 0.12): the browser's marks on the way to a quote, the + # Prumo's print generation and the time from payment event to card. + site_speed = c.execute(f'''WITH samples AS ( + SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms, + (o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms, + (o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes, + (o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms, + (o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms + FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}) + SELECT + avg(page_ms) AS page_avg, + percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n, + avg((upload_ms/1000.0)/(upload_bytes/1048576.0)) + FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg, + percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_ms/1000.0)/(upload_bytes/1048576.0)) + FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95, + count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n, + avg(analysis_ms) AS analysis_avg, + percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n, + avg(montage_ms) AS montage_avg, + percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n + FROM samples''', period).fetchone() + print_speed = c.execute(f'''WITH samples AS ( + SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds, + COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric, + (o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres + FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id + WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL + AND p.item_index < jsonb_array_length(o.snapshot->'items')) + SELECT avg(seconds) AS avg_s, + percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n, + avg(seconds/NULLIF(metres/10,0)) + FILTER (WHERE metres>0) AS per10_avg, + percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0)) + FILTER (WHERE metres>0) AS per10_p95, + count(*) FILTER (WHERE metres>0) AS per10_n + FROM samples''', period).fetchone() + card_speed = c.execute(f'''WITH samples AS ( + SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds + FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text + WHERE {REAL_ORDER} AND {within} GROUP BY o.id) + SELECT avg(seconds) AS avg_s, + percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n + FROM samples WHERE seconds >= 0''', period).fetchone() + today = datetime.now(timezone(timedelta(hours=-3))).date() + late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')} + for row in late_rows: + limit = limits.get(row['state']) + if not limit: + continue + hours = float(limit['hours']) + treatment = row.get('treatment') or {} + if row['state'] == 'rec' and treatment: + hours += float(treatment.get('hours', 24)) + if row['seconds'] > hours * 3600: + late[row['state']]['count'] += 1 + if row['day'] == today: + late[row['state']]['today'] += 1 + 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], + 'unpaid': unpaid_figures, + 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, + 'stage_limits': limits, 'late': late, + 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], + 'average_hours': hours(row['average_hours'])} for row in stages}, + 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, + 'speed': speed_figures(site_speed, print_speed, card_speed), + 'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided), + 'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'], + 'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']), + 'cents': int(row['cents'])} for row in coupons_used]} + + +def speed_figures(site, generation, card): + """Números' speed block: average and slow-case p95, in seconds per unit.""" + def pair(avg, p95, n, scale=1): + return {'average': round(float(avg)/scale, 2) if avg is not None else None, + 'p95': round(float(p95)/scale, 2) if p95 is not None else None, + 'samples': int(n or 0)} + return [ + {'key': 'page', 'label': 'Abrir o montador', 'unit': 's', + **pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)}, + {'key': 'upload', 'label': 'Subir o arquivo', 'unit': 's/MB', + **pair(site['upload_avg'], site['upload_p95'], site['upload_n'])}, + {'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's', + **pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)}, + {'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's', + **pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)}, + {'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's', + **pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])}, + {'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's', + **pair(card['avg_s'], card['p95_s'], card['n'])}, + ] + + +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