Files
dtf-system/app/api/operator/common.py
Cauê Faleiros 449b45b520
Some checks failed
Build and deploy / Validate source (push) Successful in 1m41s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
fix: the print file is written over twice as fast, and a file finished after Prova OK queues its order (#81)
#81's 91,5 m took 6 hours to generate. The PNG writer ran Pillow's row filters
and then deflate at level 6; no filter at level 1 gives the same size in under
half the time, for the file and the viewer's strips alike (1 m: 34 s -> 13 s).

Its Prova OK came while the file was still being generated, so the order stayed
in Arte recebida. The approval now also runs when the file finishes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 09:40:13 -03:00

92 lines
3.9 KiB
Python

"""Helpers and constants shared by more than one Kanban router."""
import re
from fastapi import APIRouter, HTTPException
from ... import cnpj
from ...core import db
from ...finals import FINAL_OK, TREATED # noqa: F401 (the board, files and stats use them)
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])
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', 'premium'}, 'uv': {'uvfile', 'uv'},
'folha': {'file', 'uvfile', 'premium'}, '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')