From 5910d3161fbf463c60755254955d5d4b4cb4263d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 16 Oct 2026 18:46:49 -0300 Subject: [PATCH] feat: the Tiny probe reads what a complete order needs "campos" tries each lookup a complete order needs (formas de recebimento, financial categories, sellers, intermediaries) and names the app permission to release when Tiny refuses one; it also shows Correios and Jadlog as Tiny keeps them, with their freight options. "exemplo NUMERO" prints an existing order's payment, carrier, seller, category and tags, without the customer or the address, so Site orders can copy the store's. Both only read. Co-Authored-By: Claude Opus 5.5 --- app/tiny_probe.py | 75 ++++++++++++++++++++++++++++++++++++++++++++++ tests/test_tiny.py | 36 +++++++++++++++++++++- 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 37b29e4..1b0ef41 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -5,6 +5,10 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account. python -m app.tiny_probe produtos [termo] list active products (read-only) python -m app.tiny_probe formas-envio [termo] list formas de envio, to find pickup (read-only) python -m app.tiny_probe conferir connection, the products or SKUs and pickup (read-only) + python -m app.tiny_probe campos what a complete order needs from Tiny: payment methods, + categories, sellers, Correios/Jadlog freight (read-only) + python -m app.tiny_probe exemplo NUMERO the structure of an existing order, without the + customer's details, to copy in Site orders (read-only) python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3] show the test order; --confirmar creates it @@ -64,6 +68,70 @@ def formas_envio(orders, termo, out): '. A retirada é a do tipo 6 (Customizado) que a equipe usa para retirar pessoalmente.') +# What a complete order (as the store's own orders reach Tiny) looks up, each +# with the app permission it needs in Tiny's Aplicativos screen. +LOOKUPS = (('Formas de recebimento', '/formas-recebimento', 'Forma de Recebimento (Leitura)'), + ('Categorias de receita e despesa', '/categorias-receita-despesa', 'Contas Receber (Leitura)'), + ('Vendedores', '/vendedores', 'Contatos (Leitura)'), + ('Intermediadores', '/intermediadores', 'Intermediadores (Leitura)')) +# The parts of an existing order worth copying; the customer and the address +# are left out. Every other field is listed by name only. +EXAMPLE_FIELDS = ('situacao', 'data', 'dataPrevista', 'naturezaOperacao', 'vendedor', 'transportador', + 'pagamento', 'categoria', 'ecommerce', 'intermediador', 'listaPreco', 'deposito', + 'numeroOrdemCompra', 'valorFrete', 'origemPedido', 'marcadores') + + +def short(item): + return json.dumps(item, ensure_ascii=False, separators=(', ', ': '))[:240] + + +def listed(found): + return found if isinstance(found, list) else (found.get('itens') or []) + + +def campos(orders, out): + ok = True + for label, path, permission in LOOKUPS: + try: + found = listed(orders.request('GET', path, params={'limit': 100})) + except tiny.TinyError as exc: + ok = False + denied = ': 403 ' in str(exc) or ': 401 ' in str(exc) + out(f'{label}: ' + (f'sem permissão. Libere "{permission}" no aplicativo e reconecte.' if denied + else str(exc))) + continue + out(f'{label}: {len(found)}') + for item in found: + out(' ' + short(item)) + # Correios and Jadlog, with whatever freight options Tiny keeps for them. + methods = listed(orders.request('GET', '/formas-envio', params={'limit': 100})) + for method in methods: + if not any(word in str(method.get('nome', '')).lower() for word in ('correio', 'jadlog')): + continue + out(f"Forma de envio {method.get('id')} · tipo {method.get('tipo')} · {method.get('nome')}") + try: + out(' ' + short(orders.request('GET', f"/formas-envio/{method['id']}"))) + except tiny.TinyError as exc: + out(f' {exc}') + return ok + + +def exemplo(orders, numero, out): + found = listed(orders.request('GET', '/pedidos', params={'numero': numero, 'limit': 5})) + match = [p for p in found if str(p.get('numeroPedido') or p.get('numero') or '') == str(numero)] + if not match: + out(f'Pedido {numero} não encontrado.') + return False + detail = orders.request('GET', f"/pedidos/{match[0]['id']}") + try: + detail['marcadores'] = orders.request('GET', f"/pedidos/{match[0]['id']}/marcadores") + except tiny.TinyError as exc: + detail['marcadores'] = f'não lidos: {exc}' + out(json.dumps({k: detail[k] for k in EXAMPLE_FIELDS if k in detail}, ensure_ascii=False, indent=2)) + out('Outros campos (sem valores): ' + ', '.join(sorted(k for k in detail if k not in EXAMPLE_FIELDS))) + return True + + def conferir(orders, out): ok = True for mode, setting in tiny.PRODUCT_SETTINGS.items(): @@ -143,6 +211,9 @@ def main(argv=None, orders=None, out=print): methods = commands.add_parser('formas-envio') methods.add_argument('termo', nargs='?', default='') commands.add_parser('conferir') + commands.add_parser('campos') + example = commands.add_parser('exemplo') + example.add_argument('numero') order = commands.add_parser('pedido') order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente') order.add_argument('--email', required=True) @@ -165,6 +236,10 @@ def main(argv=None, orders=None, out=print): return 0 if args.command == 'conferir': return 0 if conferir(orders, out) else 1 + if args.command == 'campos': + return 0 if campos(orders, out) else 1 + if args.command == 'exemplo': + return 0 if exemplo(orders, args.numero, out) else 1 cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit()) if len(cnpj) not in (11, 14): out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).') diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 532ce5d..8eaaf6e 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -12,6 +12,7 @@ from unittest import mock import httpx +from app import tiny as tiny_module from app.tiny import TinyError, TinyOrders, contact_payload, order_payload PAID = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, 'event': 'payment_approved', @@ -86,7 +87,10 @@ 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': - return httpx.Response(200, json={'itens': [{'id': o['id']} for o in self.orders]}) + return httpx.Response(200, json={'itens': [{'id': o['id'], 'numeroPedido': o['numeroPedido']} + for o in self.orders]}) + if request.method == 'GET' and path.endswith('/marcadores'): + return httpx.Response(200, json=[{'descricao': 'SITE DTF'}]) if request.method == 'GET' and path.startswith('/pedidos/'): wanted = int(path.rsplit('/', 1)[-1]) return httpx.Response(200, json=next(o for o in self.orders if o['id'] == wanted)) @@ -472,6 +476,36 @@ class TinyProbeTests(FakeTinyCase): self.assertIn('77\t6\tRetirar pessoalmente', text) self.assertTrue(all(method == 'GET' for method, _ in self.calls)) + def test_campos_says_which_lookup_needs_a_permission(self): + handler = self.handler + + def account(request): + path = request.url.path.removeprefix('/public-api/v3') + if path == '/formas-recebimento': + return httpx.Response(200, json={'itens': [{'id': 1, 'nome': 'Pix'}]}) + if path == '/categorias-receita-despesa': + return httpx.Response(403, json={'mensagem': 'sem permissão'}) + if path in ('/vendedores', '/intermediadores'): + return httpx.Response(200, json={'itens': []}) + return handler(request) + self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(account)) + code, text = self.probe('campos') + self.assertEqual(code, 1) + self.assertIn('Formas de recebimento: 1', text) + self.assertIn('"nome": "Pix"', text) + self.assertIn('Libere "Contas Receber (Leitura)"', text) + self.assertIn('Forma de envio 78 · tipo 1 · Correios', text) + + def test_exemplo_shows_an_order_without_the_customer(self): + self.tiny.deliver('k1', PAID) + self.orders[0].update(cliente={'nome': 'Fulano', 'cpfCnpj': '1'}, pagamento={'formaRecebimento': {'id': 1}}) + code, text = self.probe('exemplo', self.orders[0]['numeroPedido']) + self.assertEqual(code, 0) + self.assertIn('"formaRecebimento"', text) + self.assertNotIn('Fulano', text) + self.assertIn('cliente', text.splitlines()[-1]) + self.assertTrue(all(method == 'GET' for method, _ in self.calls[-3:])) + def test_order_is_shown_and_not_created_without_confirmation(self): code, text = self.probe('pedido', '--cnpj', '11.222.333/0001-81', '--email', 'a@example.test', '--celular', '16999999999')