All checks were successful
Build and deploy / Validate source (push) Successful in 13s
Build and deploy / Integration suite on a real stack (push) Successful in 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m10s
The worker looked names up inside its main loop, which also sends orders to Tiny and asks Mercado Pago about payments. Without internet, or with the registry slow, five lookups could hold that loop for most of a minute. They now run on a thread of their own, one batch at a time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
101 lines
4.2 KiB
Python
101 lines
4.2 KiB
Python
"""The company name behind a customer's CNPJ, from the public registry.
|
|
|
|
The Site asks for e-mail, CNPJ and WhatsApp only, so the Kanban showed an
|
|
e-mail where a name belongs, and a new Tiny contact was named after it. The
|
|
Receita's CNPJ registry is public, and BrasilAPI serves it without a key.
|
|
Names are looked up by the worker, never while a customer waits, and kept in
|
|
dtf_local.cnpj_names; a lookup that fails is tried again a day later.
|
|
"""
|
|
import os
|
|
|
|
import httpx
|
|
|
|
API = os.environ.get('CNPJ_LOOKUP_URL', 'https://brasilapi.com.br/api/cnpj/v1/')
|
|
# A few per minute of the worker's time is plenty: customers repeat.
|
|
PER_RUN = 5
|
|
|
|
|
|
def digits(value):
|
|
return ''.join(ch for ch in str(value or '') if ch.isdigit())
|
|
|
|
|
|
def fetch(cnpj, transport=None):
|
|
"""The registry's names for one CNPJ. An unknown CNPJ has none, and is not asked again."""
|
|
with httpx.Client(timeout=8, transport=transport) as http:
|
|
response = http.get(API + cnpj, headers={'Accept': 'application/json', 'User-Agent': 'dtf-sistema'})
|
|
if response.status_code == 404:
|
|
return {'legal_name': None, 'trade_name': None}
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
clean = lambda value: ' '.join(str(value).split()) or None if value else None
|
|
return {'legal_name': clean(data.get('razao_social')), 'trade_name': clean(data.get('nome_fantasia'))}
|
|
|
|
|
|
def pending(c, limit):
|
|
"""CNPJs of orders and recent quotes never looked up, or whose lookup failed a day ago."""
|
|
return [row['cnpj'] for row in c.execute('''WITH seen AS (
|
|
SELECT regexp_replace(snapshot->'customer'->>'cnpj', '\\D', '', 'g') AS cnpj, created_at FROM dtf_local.orders
|
|
UNION ALL
|
|
SELECT regexp_replace(draft->'customer'->>'cnpj', '\\D', '', 'g'), created_at FROM dtf_local.quotes
|
|
WHERE created_at > now() - interval '3 days')
|
|
SELECT s.cnpj FROM seen s LEFT JOIN dtf_local.cnpj_names n ON n.cnpj=s.cnpj
|
|
WHERE length(s.cnpj)=14 AND (n.cnpj IS NULL OR (n.fetched_at IS NULL AND n.failed_at < now() - interval '1 day'))
|
|
GROUP BY s.cnpj ORDER BY max(s.created_at) DESC LIMIT %s''', (limit,)).fetchall()]
|
|
|
|
|
|
def store(c, cnpj, found):
|
|
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,legal_name,trade_name,fetched_at) VALUES(%s,%s,%s,now())
|
|
ON CONFLICT (cnpj) DO UPDATE SET legal_name=EXCLUDED.legal_name, trade_name=EXCLUDED.trade_name,
|
|
fetched_at=now(), failed_at=NULL''', (cnpj, found['legal_name'], found['trade_name']))
|
|
|
|
|
|
def failed(c, cnpj):
|
|
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,failed_at) VALUES(%s,now())
|
|
ON CONFLICT (cnpj) DO UPDATE SET failed_at=now()''', (cnpj,))
|
|
|
|
|
|
def resolve(connect, limit=PER_RUN, transport=None):
|
|
"""Look up the next few CNPJs; returns how many were found."""
|
|
with connect() as c:
|
|
cnpjs = pending(c, limit)
|
|
found = 0
|
|
for cnpj in cnpjs:
|
|
try:
|
|
names = fetch(cnpj, transport)
|
|
except (httpx.HTTPError, ValueError):
|
|
with connect() as c:
|
|
failed(c, cnpj)
|
|
continue
|
|
with connect() as c:
|
|
store(c, cnpj, names)
|
|
found += 1
|
|
return found
|
|
|
|
|
|
def names(c, cnpjs):
|
|
"""{cnpj: {'legal': ..., 'trade': ...}} for the CNPJs already found."""
|
|
wanted = sorted({digits(value) for value in cnpjs} - {''})
|
|
if not wanted:
|
|
return {}
|
|
rows = c.execute('''SELECT cnpj,legal_name,trade_name FROM dtf_local.cnpj_names
|
|
WHERE cnpj=ANY(%s) AND (legal_name IS NOT NULL OR trade_name IS NOT NULL)''', (wanted,)).fetchall()
|
|
return {row['cnpj']: {'legal': row['legal_name'], 'trade': row['trade_name']} for row in rows}
|
|
|
|
|
|
def company(cnpj, connect=None, transport=None):
|
|
"""One CNPJ's names for a Tiny contact: stored, or looked up now. None if unavailable."""
|
|
if connect is None:
|
|
from .core.db import connect
|
|
cnpj = digits(cnpj)
|
|
with connect() as c:
|
|
known = names(c, [cnpj]).get(cnpj)
|
|
if known:
|
|
return known
|
|
try:
|
|
found = fetch(cnpj, transport)
|
|
except (httpx.HTTPError, ValueError):
|
|
return None
|
|
with connect() as c:
|
|
store(c, cnpj, found)
|
|
return {'legal': found['legal_name'], 'trade': found['trade_name']} if any(found.values()) else None
|