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

@@ -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()