feat: customers show by their company's name, taken from the CNPJ 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
worker now looks up each customer's CNPJ in the public registry (BrasilAPI,
no key) a few at a time, never while a customer waits, and keeps the razão
social and trade name in dtf_local.cnpj_names; a failed lookup is retried a
day later. Cards, the order panel, quotes and the search results show the
trade name (else the razão social) above the e-mail, the search finds
orders and quotes by either name, and a new Tiny contact gets the razão
social as its name and the trade name as fantasia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-05 12:19:35 -03:00
parent 581fbe6be4
commit b3c5f63553
9 changed files with 228 additions and 21 deletions

View File

@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -v
- name: Runtime and retention regressions
run: |

View File

@@ -15,7 +15,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, o
login_failed, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..printjobs import queue as queue_print_files
from .. import payments, quote_review
from .. import cnpj, 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)
@@ -122,9 +122,11 @@ def board(user=Depends(operator)):
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}, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total}
@@ -149,6 +151,12 @@ def thumbnails(c, *groups):
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'"""
@@ -197,7 +205,8 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N
ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
orders = with_print_files(c, rows[:limit])
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders)}
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
'names': company_names(c, orders)}
@router.get('/api/operator/payment-events')
@@ -259,13 +268,15 @@ def numeric(q):
def customer_match(column, q):
"""SQL and parameters matching a customer (e-mail, 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."""
"""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)
sql = f"lower({column}->'customer'->>'mail') LIKE %s"
params = [like(text)]
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")
@@ -309,7 +320,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
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)}
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
@router.get('/api/operator/search')
@@ -338,7 +349,8 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
orders = with_print_files(c, orders)
quotes = [quote_view(c, row) for row in rows]
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes)}
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(operator)):

100
app/cnpj.py Normal file
View File

@@ -0,0 +1,100 @@
"""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=10, 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

View File

@@ -226,3 +226,10 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;
-- An order's place in its column's queue, when an operator dragged it up or
-- down. Empty means "by payment time"; it is cleared when the order moves on.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision;
-- The company name behind each customer's CNPJ, from the public registry
-- (app/cnpj.py). failed_at alone: the lookup failed and is retried later.
CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
cnpj text PRIMARY KEY, legal_name text, trade_name text,
fetched_at timestamptz, failed_at timestamptz
);

View File

@@ -286,12 +286,17 @@ def money(cents):
return float(Decimal(cents) / 100)
def contact_payload(order):
def contact_payload(order, company=None):
"""A new contact, named after the company's razão social when the
registry gave it (app/cnpj.py), else the recipient or the e-mail."""
customer = order['customer']
destination = order.get('destination')
contact = {'nome': (destination or {}).get('recipient') or customer['mail'],
company = company or {}
contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'],
'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'],
'celular': customer['zap'], 'situacao': 'A'}
if company.get('trade'):
contact['fantasia'] = company['trade']
if destination:
contact['endereco'] = address(destination)
return contact
@@ -412,7 +417,7 @@ def check(auth=None, transport=None, orders=None):
class TinyOrders:
def __init__(self, auth=None, transport=None, today=None):
def __init__(self, auth=None, transport=None, today=None, names=None):
missing = [name for name in required_settings() if not os.environ.get(name)]
if auth is None and missing:
raise RuntimeError('Tiny needs ' + ', '.join(missing))
@@ -420,6 +425,8 @@ class TinyOrders:
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
self.today = today
self.skus = {}
# The company's names by CNPJ, for new contacts (app.cnpj.company).
self.names = names
def request(self, method, path, **kwargs):
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
@@ -449,7 +456,13 @@ class TinyOrders:
for entry in found.get('itens') or []:
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
return entry['id']
return self.request('POST', '/contatos', json=contact_payload(order))['id']
company = None
if self.names:
try:
company = self.names(cnpj)
except Exception: # a name is a nicety; the order must still go
company = None
return self.request('POST', '/contatos', json=contact_payload(order, company))['id']
def find(self, payload, days=SEARCH_DAYS):
"""An order a previous delivery already created, or None."""

View File

@@ -18,10 +18,12 @@ adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}
# Not yet confirmed against the client's account; see app/tiny.py.
if os.environ.get('TINY_ADAPTER') == 'tiny':
from .tiny import TinyOrders
adapters['tiny'] = TinyOrders()
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
last_tick = 0.0
last_cleanup = 0.0
last_reconcile = 0.0
last_names = 0.0
last_tiny_keepalive = 0.0
storage = LocalS3Storage()
scan_thread = None
@@ -87,6 +89,15 @@ def reconcile_payments():
from .runtime import payment
payments.reconcile(connect, payment)
def resolve_names():
"""Every minute: the company names of a few new customers' CNPJs."""
global last_names
if time.monotonic()-last_names < 60:
return
last_names = time.monotonic()
from . import cnpj
cnpj.resolve(connect)
def loop():
global last_cleanup
while True:
@@ -97,6 +108,7 @@ def loop():
last_cleanup = time.monotonic()
tiny_keepalive()
reconcile_payments()
resolve_names()
except Exception:
logging.exception('Local worker tick failed')
time.sleep(1)

View File

@@ -9,6 +9,7 @@ from urllib.parse import urlencode
from urllib.request import Request
from uuid import uuid4
import httpx
from psycopg.types.json import Jsonb
from app.core import db
@@ -125,6 +126,24 @@ def run():
assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1
assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1
client.call('/operator/stats?days=3', operator=True, expected=422)
# The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
registry.company('11222333000181', db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
board = client.call('/operator/board', operator=True)
assert board['names']['11222333000181'] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
assert str(order_id) in {o['id'] for o in found['orders']}, found
# A failed lookup is kept and not repeated within the day.
with db.connect() as c:
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
with db.connect() as c:
row = c.execute("SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'").fetchone()
assert row['fetched_at'] is None and row['failed_at'] is not None
assert '11222333000181' not in registry.pending(c, 500)
Client().call('/operator/stats', expected=401)
print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search and the numbers')
finally:
@@ -133,6 +152,7 @@ def run():
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
if __name__ == '__main__':

38
tests/test_cnpj.py Normal file
View File

@@ -0,0 +1,38 @@
"""The CNPJ registry lookup against a fake BrasilAPI. Runs where httpx is installed."""
import unittest
import httpx
from app import cnpj
def transport(status, body=None):
return httpx.MockTransport(lambda request: httpx.Response(status, json=body or {}))
class CnpjTests(unittest.TestCase):
def test_names_come_from_the_registry_tidied(self):
found = cnpj.fetch('11222333000181', transport(200, {
'razao_social': 'LOJA TESTE COMERCIO LTDA ', 'nome_fantasia': 'Loja Teste'}))
self.assertEqual(found, {'legal_name': 'LOJA TESTE COMERCIO LTDA', 'trade_name': 'Loja Teste'})
self.assertEqual(cnpj.fetch('11222333000181', transport(200, {'razao_social': 'X LTDA', 'nome_fantasia': ''})),
{'legal_name': 'X LTDA', 'trade_name': None})
def test_an_unknown_cnpj_has_no_names_and_an_outage_is_an_error(self):
self.assertEqual(cnpj.fetch('00000000000000', transport(404)), {'legal_name': None, 'trade_name': None})
with self.assertRaises(httpx.HTTPError):
cnpj.fetch('11222333000181', transport(503))
def test_new_tiny_contacts_are_named_after_the_company(self):
from app.tiny import contact_payload
order = {'customer': {'cnpj': '11222333000181', 'mail': 'loja@example.test', 'zap': '16999999999'},
'destination': None}
named = contact_payload(order, {'legal': 'LOJA TESTE LTDA', 'trade': 'Loja Teste'})
self.assertEqual((named['nome'], named['fantasia']), ('LOJA TESTE LTDA', 'Loja Teste'))
plain = contact_payload(order)
self.assertEqual(plain['nome'], 'loja@example.test')
self.assertNotIn('fantasia', plain)
if __name__ == '__main__':
unittest.main()

View File

@@ -34,7 +34,10 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul
// Uploads that have an artwork picture (the customer's browser made it). Every
// list the API returns says which, so only pictures that exist are asked for.
const THUMBS=new Set();
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));return r;};
// Company names by CNPJ, from the public registry (app/cnpj.py).
const NAMES=new Map();
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));
for(const [cnpj,name] of Object.entries(r?.names||{}))NAMES.set(cnpj,name);return r;};
let olderFinished=[], finishedMore=null;
const money=cents=>(cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
@@ -123,13 +126,15 @@ function facts(pairs){
// receives the delivery), else the e-mail. With a name, the e-mail is the
// second line, still searchable.
function buyer(content){
const c=content.customer||{}, name=(c.name||content.destination?.recipient||'').trim();
return {title:name||c.mail, mail:name?c.mail:''};
const c=content.customer||{}, company=NAMES.get(String(c.cnpj||'').replace(/\D/g,''));
// The trade name people know the shop by, else its razão social.
const name=(c.name||company?.trade||company?.legal||content.destination?.recipient||'').trim();
return {title:name||c.mail, mail:name?c.mail:'', legal:company?.legal||''};
}
function buyerBlock(content,className){
const who=buyer(content);
const box=node('div',undefined,'buyer '+(className||''));
const title=node('b',who.title);title.title=who.mail||who.title;box.append(title);
const title=node('b',who.title);title.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;box.append(title);
if(who.mail)box.append(node('span',who.mail,'buyer-mail'));
return box;
}