Pilot customers had no way to reset a forgotten password, and the 7 October meeting asked for two things that only needed the client's inputs to go live. Password recovery: "Esqueci minha senha" in Minha conta sends a link that works once, for an hour (/conta/redefinir#token, in the fragment so it never reaches a server or a Referer). Only the token's hash is stored, the e-mail's text is erased once sent, the answer never says whether an account exists, and a reset signs out every other session. Limited per address and source. Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários get one when an order is paid, a cart waits for review, or a payment needs attention. Messages are queued in the transaction that caused them and sent by the worker with retries (app/mail.py). Integrações shows an E-mail row with "Enviar teste". E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering WhatsApp) until the client's SMTP account exists; then it is only settings (docs/PORTAINER.md). The local stack keeps messages in the database and log. Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS per metre, to steer customers to PNG as the meeting asked. It is 0 until Marcus gives the amount. The Site shows it before checkout, the server charges it, Tiny gets it in the unit price, and the Kanban says it. Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP server, retry, who gets alerts), pricing unit tests, and the browser test now checks the Site total equals the server's, run with the charge at 0 and at R$ 5,00. The full CI suite passes in a CI-style stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
817 lines
47 KiB
Python
817 lines
47 KiB
Python
"""Kanban: sign-in, the board, commercial review and card movement."""
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import secrets
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Literal
|
|
from uuid import UUID
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
|
from fastapi.responses import RedirectResponse
|
|
|
|
from ..core import db
|
|
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
|
|
login_failed, password_matches, throttle)
|
|
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
|
from ..printjobs import queue as queue_print_files
|
|
from .. import cnpj, mail, payments, quote_review
|
|
from .. import tiny
|
|
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
|
|
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
|
|
from ..scanning import require_clean
|
|
|
|
router = APIRouter()
|
|
|
|
# A quote that can still become an order: waiting for review, or approved within
|
|
# the payment window. Expired ones leave the Kanban; they can never be paid.
|
|
LIVE_QUOTE = (f"(q.discarded_at IS NULL AND (q.approved_at IS NULL OR "
|
|
f"q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours'))")
|
|
|
|
@router.post('/api/operator/login')
|
|
def operator_login(body: OperatorLogin, request: Request, response: Response):
|
|
email = body.email
|
|
throttle('operator:'+email, request)
|
|
with db.connect() as c:
|
|
account = c.execute('SELECT * FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
|
if not c.execute('SELECT 1 FROM dtf_local.operators WHERE active LIMIT 1').fetchone():
|
|
raise HTTPException(503, 'Nenhuma conta de operador configurada.')
|
|
# Comparable password work whether or not the account exists or is active.
|
|
stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH
|
|
matches = password_matches(body.password, stored)
|
|
if not account or not account['active'] or not matches:
|
|
login_failed('operator:'+email)
|
|
audit('operator_login_failed', ip=client_ip(request), operator=email)
|
|
raise HTTPException(401, 'E-mail ou senha inválidos.')
|
|
token = secrets.token_urlsafe(32)
|
|
with db.connect() as c:
|
|
previous = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
|
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (previous,))
|
|
c.execute('INSERT INTO dtf_local.operator_sessions(token_hash,username) VALUES(%s,%s)',
|
|
(hashlib.sha256(token.encode()).hexdigest(), email))
|
|
c.execute('UPDATE dtf_local.operators SET last_login_at=now() WHERE id=%s', (account['id'],))
|
|
response.set_cookie('dtf_operator', token, httponly=True, secure=COOKIE_SECURE,
|
|
samesite='strict', path='/api/operator', max_age=28800)
|
|
audit('operator_login_success', operator=email)
|
|
return {'ok': True}
|
|
|
|
@router.post('/api/operator/logout')
|
|
def operator_logout(request: Request, response: Response):
|
|
with db.connect() as c:
|
|
digest = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
|
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (digest,))
|
|
response.delete_cookie('dtf_operator', path='/api/operator', httponly=True,
|
|
secure=COOKIE_SECURE, samesite='strict')
|
|
audit('operator_logout')
|
|
return {'ok': True}
|
|
|
|
def freight_status():
|
|
"""What delivery the Site offers, and the package rule it prices with."""
|
|
if freight.name != 'jadlog':
|
|
return {'provider': freight.name}
|
|
cubed = freight.cubed_kg()
|
|
return {'provider': 'jadlog', 'base_kg': str(freight.base_kg), 'per_metre_kg': str(freight.per_metre_kg),
|
|
'production_days': freight.production_days,
|
|
'box_cm': [str(side) for side in freight.box_cm] if freight.box_cm else None,
|
|
'cubage_kg_m3': str(freight.cubage_kg_m3) if freight.cubage_kg_m3 else None,
|
|
'cubed_kg': str(cubed) if cubed is not None else None,
|
|
'metres_per_box': str(freight.metres_per_box) if freight.metres_per_box else None}
|
|
|
|
|
|
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 finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').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}
|
|
|
|
|
|
@router.get('/api/operator/board')
|
|
def board(request: Request, user=Depends(operator)):
|
|
with db.connect() as c:
|
|
# Everything still in progress, however old: an operator must never lose a
|
|
# card they can act on. Finished orders are terminal and only accumulate,
|
|
# so the board carries a recent window of them and reports the true total.
|
|
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
|
|
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s",
|
|
(BOARD_FINISHED_LIMIT,)).fetchall()
|
|
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
|
|
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
|
|
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall()
|
|
approved = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}
|
|
ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall()
|
|
pending_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
|
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
|
orders = visible(request, with_print_files(c, active + list(reversed(finished))))
|
|
# A paid notification that did not become an order is money received
|
|
# for nothing the factory will make. The board carries the count; the
|
|
# Pagamentos tab pages through them until someone records a resolution.
|
|
issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
|
|
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n']
|
|
backup = backup_status(c)
|
|
quotes = [quote_view(c, q) for q in pending + approved]
|
|
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
|
|
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
|
|
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
|
|
'mail': mail.status(c)},
|
|
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
|
'finished_shown': len(finished), 'finished_total': finished_total,
|
|
'machines': [{**m, 'id': str(m['id'])} for m in c.execute(
|
|
'SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall()],
|
|
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
|
'names': company_names(c, orders, quotes),
|
|
'pending_total': pending_total, 'approved_total': approved_total}
|
|
|
|
|
|
def uploads_of(rows):
|
|
"""Every upload id an order (its snapshot) or a quote (its draft) refers to."""
|
|
ids = set()
|
|
for row in rows:
|
|
content = row.get('snapshot') or row.get('draft') or {}
|
|
for item in content.get('items') or []:
|
|
ids.update(str(uid) for uid in item.get('uploads') or [])
|
|
return ids
|
|
|
|
|
|
def thumbnails(c, *groups):
|
|
"""The uploads among these orders and quotes that have an artwork picture,
|
|
so the Kanban asks only for pictures that exist."""
|
|
ids = set().union(*(uploads_of(rows) for rows in groups))
|
|
if not ids:
|
|
return []
|
|
rows = c.execute('SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s::uuid[])',
|
|
(list(ids),)).fetchall()
|
|
return [str(r['upload_id']) for r in rows]
|
|
|
|
|
|
def company_names(c, *groups):
|
|
"""The registry's company names for these orders' and quotes' CNPJs (app/cnpj.py)."""
|
|
return cnpj.names(c, [((row.get('snapshot') or row.get('draft') or {}).get('customer') or {}).get('cnpj')
|
|
for rows in groups for row in rows])
|
|
|
|
|
|
# An item's final counts while its file is still there and scanned clean: the
|
|
# same rule that lets an order into the print queue.
|
|
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
|
|
|
|
|
def product_family(order):
|
|
"""Têxtil or UV, by the order's first item: what a machine prints."""
|
|
items = (order.get('snapshot') or {}).get('items') or [{}]
|
|
return 'uv' if items[0].get('mode') in ('uvfile', 'uv') else 'textil'
|
|
|
|
|
|
def assign_machines(c, orders):
|
|
"""Each order's machine: the one someone chose, or else the first active
|
|
machine that prints its product. None while no machine is registered."""
|
|
machines = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY created_at,name').fetchall()
|
|
by_id = {str(m['id']): m for m in machines}
|
|
for order in orders:
|
|
chosen = by_id.get(str(order.get('machine_id') or ''))
|
|
machine = chosen or next((m for m in machines if m['active'] and product_family(order) in m['products']), None)
|
|
order['machine'] = {'id': str(machine['id']), 'name': machine['name'], 'chosen': bool(chosen)} if machine else None
|
|
return orders
|
|
|
|
|
|
def visible(request, orders):
|
|
"""An operator who works on some machines sees only their orders."""
|
|
account = request.state.operator
|
|
if account['role'] != 'operador' or not account['machines']:
|
|
return orders
|
|
mine = set(account['machines'])
|
|
return [o for o in orders if o.get('machine') and o['machine']['id'] in mine]
|
|
|
|
|
|
def with_print_files(c, orders):
|
|
"""Each order with its generated print files, the items whose final file is
|
|
approved, and the customer's corrections waiting to be approved as finals."""
|
|
ids = [o['id'] for o in orders]
|
|
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name
|
|
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
|
|
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall()
|
|
finals = c.execute(f'''SELECT DISTINCT f.order_id,f.item_index FROM dtf_local.order_files f
|
|
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
|
|
# Expired ones too: once corrected, a generated file is no longer the artwork.
|
|
fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name,
|
|
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
|
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
|
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
|
# Why each order was last sent to correction, for the notice to the customer.
|
|
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
|
for order in orders:
|
|
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
|
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
|
order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id'])
|
|
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
|
for row in fixes if row['order_id'] == order['id']]
|
|
return assign_machines(c, orders)
|
|
|
|
|
|
def cursor_pair(first, second):
|
|
if (first is None) != (second is None):
|
|
raise HTTPException(422, 'Both cursor fields are required')
|
|
return first is not None
|
|
|
|
|
|
@router.get('/api/operator/orders/finished')
|
|
def finished_page(request: Request, before_created_at: datetime | None = None, before_id: UUID | None = None,
|
|
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
|
|
"""Older finished orders, newest first, beyond the board's recent window."""
|
|
paged = cursor_pair(before_created_at, before_id)
|
|
with db.connect() as c:
|
|
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin'
|
|
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
|
|
ORDER BY created_at DESC,id DESC LIMIT %s''',
|
|
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
|
orders = visible(request, with_print_files(c, rows[:limit]))
|
|
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
|
'names': company_names(c, orders)}
|
|
|
|
|
|
@router.get('/api/operator/payment-events')
|
|
def payment_events(state: Literal['open','resolved','all'] = 'open',
|
|
offset: int = Query(default=0, ge=0),
|
|
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))):
|
|
"""Payments that needed a person, newest first: open ones to act on, resolved ones as history."""
|
|
where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
|
|
with db.connect() as c:
|
|
rows = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome,
|
|
resolved_at,resolved_by,resolution
|
|
FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') ''' + where + '''
|
|
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
|
|
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
|
|
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
|
|
return {'issues': rows, 'total': total}
|
|
|
|
|
|
@router.get('/api/operator/events')
|
|
def events(provider: Literal['tiny','whatsapp'] | None = None,
|
|
status: Literal['delivered','queued','failing'] | None = None,
|
|
event: Literal['payment_approved','production_started','correction_needed','ready'] | 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('manage'))):
|
|
"""The integration send log, newest first, filtered, by page with a total."""
|
|
clauses, params = [], []
|
|
if provider:
|
|
clauses.append('provider=%s'); params.append(provider)
|
|
if status == 'delivered':
|
|
clauses.append('delivered_at IS NOT NULL')
|
|
elif status == 'queued':
|
|
clauses.append('delivered_at IS NULL AND last_error IS NULL')
|
|
elif status == 'failing':
|
|
clauses.append('delivered_at IS NULL AND last_error IS NOT NULL')
|
|
if event:
|
|
clauses.append("payload->>'event'=%s"); params.append(event)
|
|
if order:
|
|
clauses.append("payload->>'number'=%s"); params.append(str(order))
|
|
where = ('WHERE ' + ' AND '.join(clauses)) if clauses else ''
|
|
with db.connect() as c:
|
|
rows = c.execute(f'SELECT * FROM dtf_local.outbox {where} ORDER BY id DESC LIMIT %s OFFSET %s',
|
|
(*params, limit, offset)).fetchall()
|
|
total = c.execute(f'SELECT count(*) AS n FROM dtf_local.outbox {where}', params).fetchone()['n']
|
|
return {'events': rows, 'total': total}
|
|
|
|
MODES = {'textil': {'file', 'avulsa'}, 'uv': {'uvfile', 'uv'},
|
|
'folha': {'file', 'uvfile'}, 'avulsa': {'avulsa', 'uv'}}
|
|
|
|
|
|
def like(text):
|
|
"""A LIKE pattern that matches the text anywhere, its own % and _ literal."""
|
|
return '%' + re.sub(r'([\\%_])', r'\\\1', text) + '%'
|
|
|
|
|
|
def numeric(q):
|
|
"""The digits of a query made of digits and punctuation only ("#1042",
|
|
"11.222.333/0001-81", "(16) 99999-0000"); empty when it has letters."""
|
|
return '' if re.search(r'[^\W\d_]', q) else re.sub(r'\D', '', q)
|
|
|
|
|
|
def customer_match(column, q):
|
|
"""SQL and parameters matching a customer (e-mail, company name, CNPJ or
|
|
WhatsApp) in an order snapshot or a quote draft. CNPJ and phone match by
|
|
their digits, and only when nothing but digits and punctuation was typed:
|
|
the digits of an e-mail address are not a phone number."""
|
|
text, digits = q.strip().lower(), numeric(q)
|
|
cnpj = f"regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g')"
|
|
sql = (f"lower({column}->'customer'->>'mail') LIKE %s OR {cnpj} IN (SELECT n.cnpj FROM dtf_local.cnpj_names n"
|
|
" WHERE lower(n.legal_name) LIKE %s OR lower(n.trade_name) LIKE %s)")
|
|
params = [like(text)] * 3
|
|
if len(digits) >= 3:
|
|
sql += (f" OR regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g') LIKE %s"
|
|
f" OR regexp_replace(coalesce({column}->'customer'->>'zap',''),'\\D','','g') LIKE %s")
|
|
params += [like(digits), like(digits)]
|
|
return '(' + sql + ')', params
|
|
|
|
|
|
@router.get('/api/operator/quotes')
|
|
def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None,
|
|
before_id: UUID | None = None, offset: int = Query(default=0, ge=0),
|
|
limit: int = Query(default=50, ge=1, le=100),
|
|
q: str | None = Query(default=None, max_length=100),
|
|
product: Literal['textil','uv'] | None = None, layout: Literal['folha','avulsa'] | None = None,
|
|
flag: Literal['ressalva'] | None = None, user=Depends(operator)):
|
|
"""Unpaid quotes, newest first: by cursor, or by page (offset) with a total;
|
|
filtered by customer, product, layout and an accepted resolution warning."""
|
|
if (before_created_at is None) != (before_id is None):
|
|
raise HTTPException(422, 'Both quote cursor fields are required')
|
|
clauses = ['o.id IS NULL', LIVE_QUOTE, 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL']
|
|
params = []
|
|
if q and q.strip():
|
|
sql, values = customer_match('q.draft', q)
|
|
clauses.append(sql); params += values
|
|
if product or layout:
|
|
modes = set.intersection(*(MODES[k] for k in (product, layout) if k))
|
|
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'mode'=ANY(%s))")
|
|
params.append(sorted(modes))
|
|
if flag:
|
|
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'quality_status'='warning')")
|
|
where = ' AND '.join(clauses)
|
|
cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else ''
|
|
skip = 0 if before_created_at else offset
|
|
page = params + ([before_created_at, before_id] if before_created_at else []) + [limit+1, skip]
|
|
with db.connect() as c:
|
|
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE {where} {cursor}
|
|
ORDER BY q.created_at DESC,q.id DESC LIMIT %s OFFSET %s''', page).fetchall()
|
|
total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE {where}''', params).fetchone()['n']
|
|
quotes = [quote_view(c,row) for row in rows[:limit]]
|
|
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
|
|
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
|
|
|
|
|
|
@router.get('/api/operator/search')
|
|
def search(request: Request, q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
|
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
|
|
CNPJ or WhatsApp, the delivery recipient, or the order number."""
|
|
match, params = customer_match('snapshot', q)
|
|
digits = numeric(q)
|
|
sql = match + " OR lower(coalesce(snapshot->'destination'->>'recipient','')) LIKE %s"
|
|
params.append(like(q.strip().lower()))
|
|
if digits and len(digits) <= 9:
|
|
sql += ' OR number=%s'
|
|
params.append(int(digits))
|
|
# The code a customer reads out (the id's first characters, see order_code).
|
|
code = q.strip().lstrip('#').lower()
|
|
if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code):
|
|
sql += " OR replace(id::text,'-','') LIKE %s"
|
|
params.append(code + '%')
|
|
quote_match, quote_params = customer_match('q.draft', q)
|
|
with db.connect() as c:
|
|
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql}
|
|
ORDER BY created_at DESC LIMIT 8''', params).fetchall()
|
|
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
|
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
|
|
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
|
|
orders = visible(request, with_print_files(c, orders))
|
|
quotes = [quote_view(c, row) for row in rows]
|
|
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
|
'names': company_names(c, orders, quotes)}
|
|
|
|
@router.post('/api/operator/quotes/{uid}/approve')
|
|
def approve(uid: UUID, body: Review, user=Depends(can('manage'))):
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Quote not found')
|
|
return quote_review.approve(c, row, body.items, user)
|
|
|
|
@router.post('/api/operator/quotes/{uid}/test-order')
|
|
def test_order(uid: UUID, user=Depends(can('manage'))):
|
|
"""An order for an approved quote without payment, to try the Kanban,
|
|
files and print flow in production. Marked TEST on the board, never sent
|
|
to Tiny or WhatsApp, and audited."""
|
|
with db.connect() as c:
|
|
try:
|
|
quote = payments.approved_quote(c, uid)
|
|
except payments.PaymentRefused as refusal:
|
|
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
|
receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid',
|
|
'total_cents': quote['approved']['total_cents'], 'operator': user}
|
|
order, created = payments.create_order(c, quote, receipt)
|
|
if created:
|
|
audit('test_order_created', order=str(order['id']), 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}
|
|
|
|
|
|
@router.post('/api/operator/orders/{uid}/delete')
|
|
def delete_order(uid: UUID, user=Depends(can('manage'))):
|
|
"""Deletes a test order, or a paid order already cancelled, with its
|
|
history and files' records. A paid order in progress must be cancelled
|
|
first, with its reason. A test order's quote is unpaid again; a cancelled
|
|
one's is discarded, so it neither returns to Cotações nor can be paid twice.
|
|
The payment itself stays recorded, and the audit log keeps who deleted what."""
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Order not found')
|
|
test = payments.is_test(row)
|
|
if not test and not row.get('cancelled_at'):
|
|
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
|
|
# Its files leave storage too: the finals, corrections and generated PDFs,
|
|
# and the customer's originals unless the quote can still be paid (a test
|
|
# order's). The worker deletes them within a minute.
|
|
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
|
|
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
|
|
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''',
|
|
(uid, uid)).fetchall()}
|
|
candidates = produced - originals if test else produced | originals
|
|
for table in ('movements', 'order_files', 'print_files'):
|
|
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
|
|
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
|
if not test:
|
|
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
|
(user, row['quote_id']))
|
|
freed = release_files(c, candidates)
|
|
audit('order_deleted', order=row['number'], test=test, operator=user,
|
|
reason=row.get('cancel_reason') or '', files_released=freed)
|
|
return {'ok': True}
|
|
|
|
|
|
def release_files(c, uploads):
|
|
"""Expire these uploads now, except any another order or an open quote
|
|
still uses: a customer can buy the same file again. Returns how many."""
|
|
free = []
|
|
for upload in uploads:
|
|
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
|
|
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
|
|
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
|
|
WHERE i->'uploads' ? %s
|
|
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
|
|
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
|
|
AND i->'uploads' ? %s
|
|
LIMIT 1''', (upload, upload, upload, upload)).fetchone()
|
|
if not used:
|
|
free.append(upload)
|
|
if free:
|
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
|
|
AND purged_at IS NULL''', (free,))
|
|
return len(free)
|
|
|
|
|
|
@router.post('/api/operator/orders/{uid}/cancel')
|
|
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
|
"""A paid order leaves the board but keeps its payment and history. Nothing
|
|
is refunded here (that is done at the provider) and Tiny is not told."""
|
|
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 number''',
|
|
(user, body.note, uid)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
|
audit('order_cancelled', order=row['number'], operator=user)
|
|
return {'ok': True}
|
|
|
|
|
|
class MachineChoice(StrictModel):
|
|
machine_id: UUID | None = None
|
|
|
|
|
|
@router.post('/api/operator/orders/{uid}/machine')
|
|
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('produce'))):
|
|
"""Send an order to a machine, or back to the automatic choice (None)."""
|
|
with db.connect() as c:
|
|
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
|
|
raise HTTPException(404, 'Máquina não encontrada.')
|
|
row = c.execute('UPDATE dtf_local.orders SET machine_id=%s WHERE id=%s RETURNING number',
|
|
(body.machine_id, uid)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Pedido não encontrado.')
|
|
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
|
|
return {'ok': True}
|
|
|
|
|
|
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, user=Depends(can('produce'))):
|
|
"""An order's place in its column: by default its payment time; dragged,
|
|
halfway between the orders it was dropped between. It neither changes the
|
|
order's stage nor counts as activity (the stalled clock keeps running)."""
|
|
if not body.after and not body.before:
|
|
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Order not found')
|
|
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, user=Depends(can('produce'))):
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Order not found')
|
|
if body.version != row['version']:
|
|
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
|
|
if row.get('cancelled_at'):
|
|
raise HTTPException(409, 'Pedido cancelado.')
|
|
if body.state == row['state']:
|
|
return row
|
|
back = BACK.get(row['state']) == body.state
|
|
if body.state not in TRANSITIONS[row['state']] and not back:
|
|
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
|
if 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.')
|
|
if body.state in ('fil','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 colocar na fila.')
|
|
if body.state == 'cor':
|
|
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
|
|
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
|
|
(uid,row['state'],body.state,user,body.reason,back))
|
|
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
|
|
events = {'imp':'production_started','cor':'correction_needed','fin':'ready'}
|
|
if body.state in events and not back and not payments.is_test(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 ('imp','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')}
|
|
for provider, payload in (('tiny', tiny), ('whatsapp', event)):
|
|
key = f'{uid}:{events[body.state]}:{provider}' if once else f'{uid}:{changed["version"]}:{provider}'
|
|
enqueue(c, key, provider, payload)
|
|
return changed
|
|
|
|
@router.post('/api/operator/orders/{uid}/print-files')
|
|
def regenerate(uid: UUID, user=Depends(can('produce'))):
|
|
"""Queue generation again for items that failed or went to manual preparation,
|
|
and for orders paid before the generator existed."""
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT id,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Order not found')
|
|
if row['state'] not in ('rec','tra'):
|
|
raise HTTPException(409, 'Print files are generated only before the order is queued')
|
|
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
|
|
raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand')
|
|
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
|
|
audit('print_file_requeued', order=str(uid), operator=user)
|
|
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()
|
|
|
|
@router.post('/api/operator/payment-events/{uid}/resolve')
|
|
def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
|
with db.connect() as c:
|
|
row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s
|
|
WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''',
|
|
(user, body.note, uid)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'No open payment issue with this id')
|
|
audit('payment_issue_resolved', payment_event=str(uid), operator=user)
|
|
return {'ok': True}
|
|
|
|
def tiny_status():
|
|
if not tiny.configured():
|
|
return {'configured': False}
|
|
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
|
**tiny.TinyAuth().status()}
|
|
|
|
@router.post('/api/operator/tiny/connect')
|
|
def tiny_connect(user=Depends(can('manage'))):
|
|
"""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('manage'))):
|
|
"""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('manage'))):
|
|
"""The Mercado Pago account behind the configured token; reads only."""
|
|
if payment.name != 'mercadopago':
|
|
raise HTTPException(409, 'Mercado Pago não está configurado')
|
|
from ..mercadopago_probe import check
|
|
audit('mercadopago_check', operator=user)
|
|
result = check(payment.access_token)
|
|
# Whether Mercado Pago's notifications reach this server and pass the
|
|
# signature: every accepted one is recorded, a refused one is audited.
|
|
with db.connect() as c:
|
|
received = c.execute('''SELECT count(*) AS n, max(received_at) AS last FROM dtf_local.payment_events
|
|
WHERE provider='mercadopago' AND received_at > now()-interval '24 hours' ''').fetchone()
|
|
last = c.execute('''SELECT received_at,status,outcome FROM dtf_local.payment_events
|
|
WHERE provider='mercadopago' ORDER BY received_at DESC LIMIT 1''').fetchone()
|
|
refused = c.execute('''SELECT count(*) AS n FROM dtf_local.security_events
|
|
WHERE event='payment_webhook_rejected' AND created_at > now()-interval '24 hours' ''').fetchone()
|
|
result['webhooks'] = {'accepted_24h': received['n'], 'refused_24h': refused['n'], 'last': last}
|
|
return result
|
|
|
|
|
|
@router.get('/api/operator/tiny/callback')
|
|
def tiny_callback(code: str = Query('', max_length=4096), state: str = Query('', max_length=128),
|
|
error: str = Query('', max_length=128)):
|
|
"""Tiny's redirect back. Cross-site, so the operator cookie is absent: the
|
|
single-use state an operator created is what authorises it. Tiny reports a
|
|
refusal (the operator declined, or offline access is not allowed for this
|
|
application) with `error` instead of a code."""
|
|
if not tiny.configured():
|
|
raise HTTPException(503, 'Tiny application is not configured')
|
|
try:
|
|
if error == 'invalid_scope':
|
|
retry = tiny.TinyAuth().without_offline(state)
|
|
audit('tiny_offline_refused')
|
|
return RedirectResponse(retry, status_code=303)
|
|
if error or not code:
|
|
raise tiny.TinyError(f'Tiny returned {error or "no code"}')
|
|
who = tiny.TinyAuth().complete(code, state)
|
|
except tiny.TinyError:
|
|
audit('tiny_connect_failed')
|
|
return RedirectResponse('/?tiny=failed', status_code=303)
|
|
audit('tiny_connected', operator=who)
|
|
return RedirectResponse('/?tiny=connected', status_code=303)
|
|
|
|
@router.get('/api/operator/orders/{uid}/history')
|
|
def history(uid: UUID, user=Depends(operator)):
|
|
with db.connect() as c:
|
|
return c.execute('SELECT * FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (uid,)).fetchall()
|
|
|
|
@router.get('/api/operator/uploads/{uid}/thumbnail')
|
|
def thumbnail(uid: UUID, user=Depends(operator)):
|
|
"""The browser-made picture of an artwork. Cached by the operator's browser:
|
|
the board is redrawn on every refresh."""
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'No picture for this upload')
|
|
return Response(bytes(row['data']), media_type=row['mime'],
|
|
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
|
|
|
|
# Real work only: an operator's test order and a cancelled one are not production.
|
|
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'"
|
|
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
|
|
|
|
|
@router.get('/api/operator/stats')
|
|
def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(operator)):
|
|
"""Production numbers from what the board already records: orders paid in
|
|
the period, how long each stage holds an order, and what is waiting now."""
|
|
# From the start of the first local day of the period.
|
|
since = ("o.created_at >= (((now() AT TIME ZONE 'America/Sao_Paulo')::date - make_interval(days => %s - 1))"
|
|
" AT TIME ZONE 'America/Sao_Paulo')")
|
|
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
|
with db.connect() as c:
|
|
total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents,
|
|
COALESCE(sum({metres}),0) AS metres,
|
|
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
|
|
AND m.to_state='cor' AND NOT m.back)) AS corrected
|
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone()
|
|
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
|
|
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
|
|
GROUP BY 1''', (days,)).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 {since}
|
|
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 {since})
|
|
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
|
|
stages = c.execute(f'''SELECT state, count(*) AS orders,
|
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours
|
|
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', (days, days)).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)) / 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 {since}''', (days,)).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()
|
|
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
|
series = []
|
|
for offset in range(days - 1, -1, -1):
|
|
day = today - 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': days, 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
|
'corrected': total['corrected'], 'daily': series,
|
|
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
|
'stages': {row['state']: {'orders': row['orders'], 'median_hours': hours(row['median_hours'])} for row in stages},
|
|
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}}
|
|
|
|
|
|
@router.get('/api/operator/queue/finals')
|
|
def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))):
|
|
"""The approved final files of every order in the print queue, in queue
|
|
order, each named after its order so a folder of them stays readable. The
|
|
browser downloads them straight from storage: a zip of multi-GB sheets
|
|
would go through the server."""
|
|
with db.connect() as c:
|
|
rows = c.execute(f'''SELECT o.number,f.item_index,f.upload_id,u.object_key,u.name 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='fil' AND o.cancelled_at IS NULL AND {FINAL_OK}
|
|
ORDER BY COALESCE(o.queue_key, extract(epoch FROM o.created_at)),o.id,f.item_index,f.created_at''').fetchall()
|
|
# A machine's operator downloads only that machine's queue.
|
|
queued = assign_machines(c, c.execute("SELECT * FROM dtf_local.orders WHERE state='fil' AND cancelled_at IS NULL").fetchall())
|
|
mine = {o['number'] for o in visible(request, queued)}
|
|
rows = [row for row in rows if row['number'] in mine]
|
|
files, names = [], set()
|
|
for row in rows:
|
|
prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
|
|
name = row['name'] if row['name'].startswith(prefix) else f"{prefix}-{row['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({'number': row['number'], 'item': row['item_index'] + 1, 'name': name,
|
|
'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)})
|
|
# 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}
|
|
|
|
|
|
@router.get('/api/operator/uploads/{uid}/download')
|
|
def download(uid: UUID, user=Depends(operator)):
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Completed upload not found')
|
|
if row['expires_at'] <= datetime.now(timezone.utc):
|
|
raise HTTPException(410, 'Artwork retention expired')
|
|
require_clean(row)
|
|
return {'name':row['name'], 'url':storage.download(row['object_key'],row['name']), 'expires_in':300}
|