diff --git a/app/tiny.py b/app/tiny.py index 4d4ea45..b501047 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -955,11 +955,14 @@ class TinyOrders: tiny_id, situacao = existing.get('id'), existing.get('situacao') else: contact_id, seller = self.contact(payload['order']) - created = self.request('POST', '/pedidos', json=order_payload( - payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping, - contact_seller=seller)) + body = order_payload(payload, contact_id, self.today, product_id=self.product_id, + shipping=self.shipping, contact_seller=seller) + sent_seller = (body.get('vendedor') or {}).get('id') + created = self.request('POST', '/pedidos', json=body) receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created', - 'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))} + 'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido')), + # Which seller went, so a missing one can be traced (#237). + 'seller': sent_seller} tiny_id, situacao = created.get('id'), ABERTA # Tagged before it is approved, so a failure here is retried while the order is still open. if situacao == ABERTA: diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 07953a8..890cc2e 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -9,6 +9,8 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account. 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 vendedor NUMERO why an order has no seller: the order's contact and its seller, + what the integration's own search and reading find (read-only) 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 @@ -126,6 +128,63 @@ def campos(orders, out): return ok +def order_detail(orders, numero): + 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)] + return orders.request('GET', f"/pedidos/{match[0]['id']}") if match else None + + +def seller_label(seller): + seller = seller or {} + return f"{seller.get('nome') or '?'} (id {seller['id']})" if seller.get('id') else 'nenhum' + + +def vendedor(orders, numero, out): + """Why an order reached Tiny without a seller (Marcus, 2026-12-02, #237): + the integration reads the seller from the contact it finds by CPF/CNPJ + (TinyOrders.contact) and sends it as vendedor.id. Read-only: it shows the + order's contact, that contact's seller, and what the integration's own + search and reading give today.""" + detail = order_detail(orders, numero) + if not detail: + out(f'Pedido {numero} não encontrado.') + return False + out(f"Vendedor no pedido {numero}: {seller_label(detail.get('vendedor'))}") + client = detail.get('cliente') or {} + contact_id = client.get('id') + document = ''.join(ch for ch in str(client.get('cpfCnpj') or '') if ch.isdigit()) + out(f'Contato do pedido: id {contact_id or "?"}') + if contact_id: + registered = orders.request('GET', f'/contatos/{contact_id}').get('vendedor') + out(f'Vendedor no cadastro desse contato hoje: {seller_label(registered)} · campo lido: ' + + json.dumps(registered, ensure_ascii=False)) + if not document: + out('O pedido não traz o CPF/CNPJ do contato; a busca da integração não pôde ser repetida.') + return True + same = [] + for form in tiny.search_forms(document): + for entry in listed(orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': 5})): + if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == document \ + and entry['id'] not in [e['id'] for e in same]: + same.append(entry) + out(f'Contatos com o mesmo CPF/CNPJ: {len(same)}') + for entry in same: + out(f" id {entry['id']} · vendedor {seller_label(entry.get('vendedor'))}") + found = orders.find_contact(document) + seller = orders.contact_seller(found) if found else None + out(f'A integração encontra o contato id {found or "nenhum"} e lê o vendedor: ' + + (f'id {seller}' if seller else 'nenhum')) + if found and contact_id and found != contact_id: + out('Conclusão: a busca da integração cai em outro contato que não o do pedido.') + elif seller and not (detail.get('vendedor') or {}).get('id'): + out('Conclusão: a integração lê o vendedor hoje e o pedido ficou sem ele. Ou o Tiny não guardou o ' + 'vendedor enviado, ou o cadastro recebeu o vendedor depois do pedido. O teste "pedido ... ' + '--confirmar" com este CPF/CNPJ separa os dois.') + elif not seller: + out('Conclusão: a integração não lê vendedor neste contato, então o pedido foi sem.') + return True + + 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)] @@ -194,9 +253,11 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): company = orders.names(cnpj) if orders.names else None name = tiny.contact_payload(payload['order'], company)['nome'] out(f'Contato {tiny.punctuated(cnpj)}: não existe; será criado como "{name}"') + seller = orders.contact_seller(known) if known else None + out('Vendedor do cadastro do contato: ' + (f'id {seller}' if seller else 'nenhum')) out('Pedido que será enviado:') out(json.dumps(tiny.order_payload(payload, known or 0, product_id=orders.product_id, - shipping=orders.shipping), + shipping=orders.shipping, contact_seller=seller), ensure_ascii=False, indent=2)) out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)') if not confirm: @@ -220,6 +281,17 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): shop = orders.request('GET', f"/pedidos/{first['tiny_id']}").get('ecommerce') or {} out(f"E-commerce no Tiny: numeroPedidoEcommerce {shop.get('numeroPedidoEcommerce') or '(vazio)'}" + (f" · canal {shop.get('nome') or '?'} (id {shop['id']})" if shop.get('id') else ' · sem canal')) + # The seller sent is the one Tiny kept (Marcus, 2026-12-02, #237). + kept = (orders.request('GET', f"/pedidos/{first['tiny_id']}").get('vendedor') or {}).get('id') + sent = first.get('seller') + seller_kept = not sent or kept == sent + if first.get('status') != 'created': + out(f'Vendedor: o pedido já existia, nada foi enviado agora; no Tiny: {kept or "nenhum"}.') + elif sent: + out(f'OK: o Tiny gravou o vendedor enviado (id {sent}).' if kept == sent else + f'FALHA: mandamos o vendedor id {sent} e o Tiny gravou {kept or "nenhum"}.') + else: + out('Vendedor: nenhum enviado (o contato não tem vendedor no cadastro).') numbered = shop.get('numeroPedidoEcommerce') == wanted if not numbered: out(f'FALHA: o Tiny não guardou {wanted} em numeroPedidoEcommerce.') @@ -227,7 +299,7 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}") found_again = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id'] out('OK: o reenvio encontrou o mesmo pedido.' if found_again else 'FALHA: o reenvio não devolveu o mesmo pedido.') - return numbered and found_again + return numbered and found_again and seller_kept finally: # Whatever happened above, the test order does not stay open. cancelar(orders, first['tiny_id'], out) @@ -335,6 +407,8 @@ def main(argv=None, orders=None, out=print): commands.add_parser('campos') example = commands.add_parser('exemplo') example.add_argument('numero') + seller = commands.add_parser('vendedor') + seller.add_argument('numero') cancel = commands.add_parser('cancelar') cancel.add_argument('tiny_id', type=int) order = commands.add_parser('pedido') @@ -366,6 +440,8 @@ def main(argv=None, orders=None, out=print): return 0 if conferir(orders, out) else 1 if args.command == 'campos': return 0 if campos(orders, out) else 1 + if args.command == 'vendedor': + return 0 if vendedor(orders, args.numero, out) else 1 if args.command == 'exemplo': return 0 if exemplo(orders, args.numero, out) else 1 if args.command == 'cancelar': diff --git a/tests/test_tiny.py b/tests/test_tiny.py index edd1a11..77837c4 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -886,6 +886,49 @@ class TinyProbeTests(FakeTinyCase): self.assertIn('FALHA: o Tiny não guardou DTF-TESTE-', text) self.assertEqual(self.orders[0]['situacao'], 2) + def test_the_supervised_order_says_whether_tiny_kept_the_seller(self): + # Marcus, 2026-12-02 (#237): the contact has a seller and the order came without. + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977226210, 'nome': 'Kedma'}}) + code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test', + '--celular', '16999999999', '--confirmar') + self.assertEqual(code, 0, text) + self.assertIn('Vendedor do cadastro do contato: id 977226210', text) + self.assertIn('"vendedor": {\n "id": 977226210', text) + self.assertIn('OK: o Tiny gravou o vendedor enviado (id 977226210).', text) + + def dropping(request): + if request.method == 'POST' and request.url.path.endswith('/pedidos'): + body = {k: v for k, v in json.loads(request.content).items() if k != 'vendedor'} + request = httpx.Request(request.method, request.url, headers=request.headers, content=json.dumps(body)) + return self.handler(request) + self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(dropping), today=date(2026, 9, 24)) + self.orders.clear() + code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test', + '--celular', '16999999999', '--confirmar') + self.assertEqual(code, 1, text) + self.assertIn('FALHA: mandamos o vendedor id 977226210 e o Tiny gravou nenhum.', text) + + def test_vendedor_tells_why_an_order_has_no_seller(self): + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977226210, 'nome': 'Kedma'}}) + receipt = self.tiny.deliver('k1', PAID) + # Which seller went is kept with the delivery. + self.assertEqual(receipt['seller'], 977226210) + order = self.orders[0] + order['cliente'] = {'id': 321, 'cpfCnpj': '11.222.333/0001-81'} + order.pop('vendedor') # as Tiny showed #237 + code, text = self.probe('vendedor', order['numeroPedido']) + self.assertEqual(code, 0, text) + self.assertIn(f"Vendedor no pedido {order['numeroPedido']}: nenhum", text) + self.assertIn('Vendedor no cadastro desse contato hoje: Kedma (id 977226210)', text) + self.assertIn('A integração encontra o contato id 321 e lê o vendedor: id 977226210', text) + self.assertIn('Conclusão: a integração lê o vendedor hoje e o pedido ficou sem ele.', text) + self.assertNotIn('PUT', [method for method, _ in self.calls if method != 'POST']) + # A second contact with the same document, found first, is named. + self.contacts.insert(0, {'id': 320, 'cpfCnpj': '11.222.333/0001-81'}) + code, text = self.probe('vendedor', order['numeroPedido']) + self.assertIn('Contatos com o mesmo CPF/CNPJ: 2', text) + self.assertIn('Conclusão: a busca da integração cai em outro contato que não o do pedido.', text) + def test_cancelar_touches_only_test_orders(self): self.tiny.deliver('k1', PAID) real = self.orders[0]