From 1ad761ec5306b89386eb4a81e627268b228f20f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 27 Oct 2026 15:56:56 -0300 Subject: [PATCH] feat: the Tiny probe's diagnostico finds which part of an order Tiny refuses Tiny answered the test order with a bare 403. The command sends the same test order whole, then without one part at a time (ecommerce, pagamento, transportador, dataPrevista), then with only the essentials, stops at the first version Tiny accepts and cancels it at once. It needs a contact that already exists and never creates one. Co-Authored-By: Claude Opus 5.5 --- app/tiny_probe.py | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/test_tiny.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 5dff2fe..341c1d9 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -12,6 +12,9 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account. python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3] show the test order; --confirmar creates it, then cancels it python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else + python -m app.tiny_probe diagnostico --cpf ... --email ... --celular ... + when Tiny refuses the order: sends it again without one + part at a time, stops at the first it accepts (cancelled) The test order goes through TinyOrders.deliver, exactly as the worker sends a paid order. The duplicate guard is then proven read-only first (the order must @@ -216,6 +219,39 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): cancelar(orders, first['tiny_id'], out) +def diagnostico(orders, payload, out): + """Which part of the order Tiny refuses, when it says only 403. The same + test order is sent whole, then without one part at a time, then with only + what an order cannot go without; the first version Tiny accepts names the + part, and that order is cancelled at once. The contact must exist already: + this never creates one.""" + cnpj = payload['order']['customer']['cnpj'] + known = orders.find_contact(cnpj) + if not known: + out(f'Contato {tiny.punctuated(cnpj)} não existe no Tiny; use o CPF de um contato que já existe.') + return False + out(f'Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})') + full = tiny.order_payload(payload, known, product_id=orders.product_id, shipping=orders.shipping) + without = lambda key: {k: v for k, v in full.items() if k != key} + versions = [('completo', full)] + [(f'sem {key}', without(key)) for key in + ('ecommerce', 'pagamento', 'transportador', 'dataPrevista') + if key in full] + versions.append(('só o essencial (data, contato, itens, nº de compra)', + {k: full[k] for k in ('data', 'idContato', 'numeroOrdemCompra', 'itens')})) + for name, body in versions: + try: + created = orders.request('POST', '/pedidos', json=body) + except tiny.TinyError as exc: + out(f'{name}: recusado ({exc})') + continue + out(f"{name}: ACEITO (Tiny id {created.get('id')}). O que falta no completo é o que foi tirado aqui.") + cancelar(orders, created.get('id'), out) + return True + out('Todas as versões foram recusadas, até a essencial: não é o conteúdo do pedido, é a permissão ' + 'do usuário do Tiny para incluir pedidos de venda.') + return False + + def cancelar(orders, tiny_id, out): """Cancel a test order through the API and read it back. Only orders this probe made (purchase order DTF-TESTE-...) are touched.""" @@ -260,6 +296,10 @@ def main(argv=None, orders=None, out=print): order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file') order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)') order.add_argument('--confirmar', action='store_true') + probe = commands.add_parser('diagnostico') + probe.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF de um contato que já existe') + probe.add_argument('--email', required=True) + probe.add_argument('--celular', required=True) args = parser.parse_args(argv) if orders is None: load_secret_files() @@ -285,6 +325,8 @@ def main(argv=None, orders=None, out=print): if len(cnpj) not in (11, 14): out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).') return 2 + if args.command == 'diagnostico': + return 0 if diagnostico(orders, test_order(cnpj, args.email, args.celular, 'file'), out) else 1 try: metres = Decimal(args.metros.replace(',', '.')) except InvalidOperation: diff --git a/tests/test_tiny.py b/tests/test_tiny.py index a87a148..d722eeb 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -584,6 +584,50 @@ class TinyProbeTests(FakeTinyCase): self.assertIn('77\t6\tRetirar pessoalmente', text) self.assertTrue(all(method == 'GET' for method, _ in self.calls)) + def test_diagnostico_finds_the_part_tiny_refuses(self): + handler = self.handler + + def refusing(request): + path = request.url.path.removeprefix('/public-api/v3') + if request.method == 'POST' and path == '/pedidos' and 'ecommerce' in json.loads(request.content): + self.calls.append((request.method, path)) + return httpx.Response(403, text='') + return handler(request) + self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing)) + args = ('diagnostico', '--cpf', '130.323.978-71', '--email', 'a@example.test', '--celular', '16999999999') + # Never creates a contact: one that exists is required. + code, text = self.probe(*args) + self.assertEqual(code, 1) + self.assertIn('não existe no Tiny', text) + self.assertNotIn(('POST', '/contatos'), self.calls) + self.assertNotIn(('POST', '/pedidos'), self.calls) + self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'}) + code, text = self.probe(*args) + self.assertEqual(code, 0, text) + self.assertIn('completo: recusado', text) + self.assertIn('sem ecommerce: ACEITO', text) + # The one order Tiny accepted is cancelled at once, and nothing after it is sent. + self.assertEqual(len(self.orders), 1) + self.assertEqual(self.orders[0]['situacao'], tiny_module.CANCELADA) + self.assertIn('cancelado no Tiny', text) + self.assertNotIn(('POST', '/contatos'), self.calls) + + def test_diagnostico_blames_the_permission_when_all_are_refused(self): + handler = self.handler + + def refusing(request): + if request.method == 'POST' and request.url.path.endswith('/pedidos'): + return httpx.Response(403, text='') + return handler(request) + self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing)) + self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'}) + code, text = self.probe('diagnostico', '--cpf', '13032397871', '--email', 'a@example.test', + '--celular', '16999999999') + self.assertEqual(code, 1) + self.assertIn('só o essencial', text) + self.assertIn('permissão do usuário do Tiny', text) + self.assertEqual(self.orders, []) + def test_campos_says_which_lookup_needs_a_permission(self): handler = self.handler