A pure move: the 48 Kanban routes, their code and comments are unchanged, grouped in session, board, quotes, orders, rework, integrations, stats and files, with shared helpers in common. The fast CI check now compiles the package's files too (app/**/*.py does not reach a third level without globstar). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
105 lines
4.7 KiB
Python
105 lines
4.7 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
|
|
|
|
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')
|