From c266bea68471df90c83553526b5cf72613a1426a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 21 Oct 2026 15:08:31 -0300 Subject: [PATCH] fix: Tiny contacts and orders are searched by the punctuated CPF/CNPJ, as Tiny keeps them An existing customer was not found by the bare digits, so each Site order would have created a duplicate contact, and a resent order a duplicate order. Co-Authored-By: Claude Opus 5.5 --- app/tiny.py | 52 ++++++++++++++++++++++++++++++++++++---------- app/tiny_probe.py | 9 ++++---- tests/test_tiny.py | 39 ++++++++++++++++++++++++++++++---- 3 files changed, 80 insertions(+), 20 deletions(-) diff --git a/app/tiny.py b/app/tiny.py index 3700084..6f8dd53 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -384,6 +384,24 @@ def money(cents): return float(Decimal(cents) / 100) +def punctuated(document): + """A CPF or CNPJ as Tiny keeps it, 130.323.978-71 or 11.222.333/0001-81: + its searches match that exact text, so the bare digits find nothing.""" + d = ''.join(ch for ch in str(document) if ch.isdigit()) + if len(d) == 11: + return f'{d[:3]}.{d[3:6]}.{d[6:9]}-{d[9:]}' + if len(d) == 14: + return f'{d[:2]}.{d[2:5]}.{d[5:8]}/{d[8:12]}-{d[12:]}' + return d + + +def search_forms(document): + """Punctuated first, as Tiny keeps it; then the bare digits, for a contact + someone typed in without punctuation.""" + d = ''.join(ch for ch in str(document) if ch.isdigit()) + return list(dict.fromkeys((punctuated(d), d))) + + 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 customer's name, else the @@ -394,7 +412,7 @@ def contact_payload(order, company=None): company = company or {} contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient') or customer['mail']), - 'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'], + 'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': punctuated(customer['cnpj']), 'email': customer['mail'], 'celular': customer['zap'], 'situacao': 'A'} if company.get('trade'): contact['fantasia'] = company['trade'] @@ -641,12 +659,20 @@ class TinyOrders: self.skus[code] = int(match[0]['id']) return self.skus[code] + def find_contact(self, cnpj): + """The id of the customer's existing contact, or None.""" + for form in search_forms(cnpj): + found = self.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': 5}) + 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 None + def contact(self, order): cnpj = order['customer']['cnpj'] - found = self.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5}) - 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'] + known = self.find_contact(cnpj) + if known: + return known company = None if self.names and len(cnpj) == 14: try: @@ -659,12 +685,16 @@ class TinyOrders: """An order a previous delivery already created, or None.""" wanted = purchase_order(payload['number']) since = ((self.today or local_today()) - timedelta(days=days)).isoformat() - found = self.request('GET', '/pedidos', params={'cpfCnpj': payload['order']['customer']['cnpj'], - 'dataInicial': since, 'limit': 100}) - for entry in found.get('itens') or []: - detail = self.request('GET', f"/pedidos/{entry['id']}") - if detail.get('numeroOrdemCompra') == wanted: - return detail + seen = set() + for form in search_forms(payload['order']['customer']['cnpj']): + found = self.request('GET', '/pedidos', params={'cpfCnpj': form, 'dataInicial': since, 'limit': 100}) + for entry in found.get('itens') or []: + if entry['id'] in seen: + continue + seen.add(entry['id']) + detail = self.request('GET', f"/pedidos/{entry['id']}") + if detail.get('numeroOrdemCompra') == wanted: + return detail return None def tag(self, tiny_id, known=False): diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 10ef09f..595062e 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -167,17 +167,16 @@ def conferir(orders, out): def pedido(orders, payload, confirm, out, wait=time.sleep): cnpj = payload['order']['customer']['cnpj'] - contacts = orders.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5}).get('itens') or [] - known = [c for c in contacts if ''.join(ch for ch in str(c.get('cpfCnpj') or '') if ch.isdigit()) == cnpj] + known = orders.find_contact(cnpj) if known: - out(f"Contato {cnpj}: já existe no Tiny (id {known[0]['id']})") + out(f"Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})") else: # Named as the worker names a new customer: the company in the CNPJ registry. company = orders.names(cnpj) if orders.names else None name = tiny.contact_payload(payload['order'], company)['nome'] - out(f'Contato {cnpj}: não existe; será criado como "{name}"') + out(f'Contato {tiny.punctuated(cnpj)}: não existe; será criado como "{name}"') out('Pedido que será enviado:') - out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id, + out(json.dumps(tiny.order_payload(payload, known or 0, product_id=orders.product_id, shipping=orders.shipping), ensure_ascii=False, indent=2)) out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)') diff --git a/tests/test_tiny.py b/tests/test_tiny.py index f4c6bde..f071a6c 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -65,6 +65,7 @@ class FakeTinyCase(unittest.TestCase): path = request.url.path.removeprefix('/public-api/v3') self.calls.append((request.method, path)) assert request.headers['authorization'] == 'Bearer access-1' + # Like Tiny: cpfCnpj matches the text the contact was saved with, punctuation and all. if request.method == 'GET' and path == '/contatos': cnpj = request.url.params.get('cpfCnpj') return httpx.Response(200, json={'itens': [c for c in self.contacts if cnpj in (None, c['cpfCnpj'])]}) @@ -94,8 +95,11 @@ class FakeTinyCase(unittest.TestCase): next(o for o in self.orders if o['id'] == wanted)['situacao'] = json.loads(request.content)['situacao'] return httpx.Response(204) if request.method == 'GET' and path == '/pedidos': + cnpj = request.url.params.get('cpfCnpj') + owners = {c['id'] for c in self.contacts if cnpj in (None, c['cpfCnpj'])} return httpx.Response(200, json={'itens': [{'id': o['id'], 'numeroPedido': o['numeroPedido']} - for o in self.orders]}) + for o in self.orders + if cnpj is None or o.get('idContato') in owners]}) if path.startswith('/pedidos/') and path.endswith('/marcadores'): wanted = int(path.split('/')[2]) if request.method == 'GET': @@ -135,7 +139,7 @@ class TinyTests(FakeTinyCase): pedido['enderecoEntrega']['nomeDestinatario']), ('14400000', '10', 'Loja Teste')) contact = contact_payload(PAID['order']) self.assertEqual((contact['tipoPessoa'], contact['cpfCnpj'], contact['endereco']['uf']), - ('J', '11222333000181', 'SP')) + ('J', '11.222.333/0001-81', 'SP')) pickup = order_payload({**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}, 1) self.assertNotIn('enderecoEntrega', pickup) @@ -150,10 +154,29 @@ class TinyTests(FakeTinyCase): self.assertEqual(self.calls.count(('POST', '/contatos')), 1) def test_existing_contact_is_reused(self): - self.contacts.append({'id': 321, 'cpfCnpj': '11222333000181'}) + # As Tiny keeps it: found only by the punctuated CNPJ. + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81'}) self.tiny.deliver('k1', PAID) self.assertNotIn(('POST', '/contatos'), self.calls) self.assertEqual(self.orders[0]['idContato'], 321) + # The order is found again by the same contact: a resend creates nothing. + self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created') + self.assertEqual(len(self.orders), 1) + + def test_a_contact_typed_without_punctuation_is_found_too(self): + self.contacts.append({'id': 322, 'cpfCnpj': '11222333000181'}) + self.tiny.deliver('k1', PAID) + self.assertNotIn(('POST', '/contatos'), self.calls) + self.assertEqual(self.orders[0]['idContato'], 322) + self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created') + self.assertEqual(len(self.orders), 1) + + def test_an_existing_cpf_contact_is_found_by_its_punctuated_cpf(self): + self.contacts.append({'id': 760799765, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'}) + person = {**PAID, 'order': {**PAID['order'], 'customer': {**PAID['order']['customer'], 'cnpj': '13032397871'}}} + self.tiny.deliver('k-cpf', person) + self.assertNotIn(('POST', '/contatos'), self.calls) + self.assertEqual(self.orders[0]['idContato'], 760799765) def test_a_cpf_customer_is_a_person_and_not_looked_up_in_the_company_registry(self): looked_up = [] @@ -161,7 +184,7 @@ class TinyTests(FakeTinyCase): person = {**PAID, 'order': {**PAID['order'], 'customer': {**PAID['order']['customer'], 'cnpj': '52998224725'}}} self.tiny.deliver('k-cpf', person) self.assertEqual((self.contacts[0]['tipoPessoa'], self.contacts[0]['cpfCnpj'], self.contacts[0]['nome']), - ('F', '52998224725', 'Loja Teste')) + ('F', '529.982.247-25', 'Loja Teste')) # With the name the Site now asks for, the contact is the person's. named = {**person['order'], 'customer': {**person['order']['customer'], 'name': 'Maria da Silva'}} self.assertEqual(contact_payload(named)['nome'], 'Maria da Silva') @@ -575,6 +598,14 @@ class TinyProbeTests(FakeTinyCase): self.assertEqual(self.orders, []) self.assertTrue(all(method == 'GET' for method, _ in self.calls)) + def test_an_existing_contact_is_shown_as_reused(self): + self.contacts.append({'id': 760799765, 'cpfCnpj': '130.323.978-71'}) + code, text = self.probe('pedido', '--cpf', '13032397871', '--email', 'a@example.test', + '--celular', '16999999999') + self.assertEqual(code, 0) + self.assertIn('Contato 130.323.978-71: já existe no Tiny (id 760799765)', text) + self.assertIn('"idContato": 760799765', text) + def test_confirmed_order_is_created_once_and_found_on_resend(self): code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test', '--celular', '16999999999', '--modo', 'uv', '--confirmar')