fix: a Tiny order goes to the customer's live contact, never a deleted one, and takes its seller (Marcus, 2026-12-02, #237)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 9m6s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m25s

Tiny lists deleted contacts (situação "E") beside the live one, a newer one
first. The integration took the first contact with the CPF/CNPJ, so #237
(DTF-237) went to a deleted Vaneska without a seller while the active one
had Kedma, and Dropstar added the seller by hand on every such order. The
contact is now chosen among the live ones: active before inactive, one with
a seller before one without, then Tiny's order. Live registrations naming
different sellers send none and reach Sentry, since which is right is
Dropstar's to say. Only deleted ones: a new contact, as for a new customer.

"tiny_probe vendedores [--desde]" (read-only) sorts every order sent to Tiny
since the seller rule (2026-11-27) by why its seller is what it is, so the
other orders can be checked; "vendedor NUMERO" now shows each contact's
situação.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-12-02 16:23:47 -03:00
parent 6c7af233bc
commit f23b64bebf
3 changed files with 216 additions and 14 deletions

View File

@@ -488,6 +488,16 @@ def search_forms(document):
return list(dict.fromkeys((punctuated(d), d)))
def digits(value):
return ''.join(ch for ch in str(value or '') if ch.isdigit())
def seller_id(contact):
"""The seller id in a contact (vendedor.id), or None for none or 0."""
seller = ((contact or {}).get('vendedor') or {}).get('id')
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None
def list_sellers(orders, pages=10):
"""Tiny's sellers (vendedores) as [{id, name}], for the Kanban user a
Venda's seller comes from (Marcus, 2026-11-17). v3 names the seller on
@@ -858,20 +868,60 @@ 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."""
def contact_choice(self, cnpj):
"""(the id of the customer's contact to use or None, the distinct
sellers among the usable ones).
Tiny keeps deleted contacts (situação "E") and lists them beside the
live one, a newer one first: #237 went to a deleted Vaneska without a
seller while the active one had Kedma (Marcus, 2026-12-02). A deleted
contact is never used. Among the rest an active one comes before an
inactive one, and one with a seller before one without, since the
order carries the seller of the customer's registration (2026-11-26);
then Tiny's own order."""
seen, usable, sellers = set(), [], set()
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']
if entry['id'] in seen or digits(entry.get('cpfCnpj')) != cnpj:
continue
seen.add(entry['id'])
detail = self.contact_detail(entry['id']) or entry
situacao = detail.get('situacao', entry.get('situacao'))
if situacao == 'E':
continue
seller = seller_id(detail)
if seller:
sellers.add(seller)
usable.append(((situacao or 'A') != 'A', seller is None, len(usable), entry['id']))
return (min(usable)[-1] if usable else None), sellers
def find_contact(self, cnpj):
"""The id of the customer's contact to use (contact_choice), or None."""
return self.contact_choice(cnpj)[0]
def contact_detail(self, contact_id):
"""A contact as Tiny has it; None when Tiny refuses the reading, so
the listing decides. A busy or unavailable Tiny retries the delivery."""
try:
return self.request('GET', f'/contatos/{contact_id}')
except (TinyRateLimit, TinyUnavailable):
raise
except TinyError:
return None
def contact(self, order):
"""The customer's contact id, and the seller of an existing one."""
cnpj = order['customer']['cnpj']
known = self.find_contact(cnpj)
known, sellers = self.contact_choice(cnpj)
if known:
if len(sellers) > 1:
# Two live registrations of one customer with different
# sellers: which one is right is Dropstar's to say, so the
# order goes without, as before, and Sentry hears of it.
logging.error('Tiny: the contacts of %s name different sellers (%s); the order goes without one',
punctuated(cnpj), ', '.join(map(str, sorted(sellers))))
return known, None
return known, self.contact_seller(known)
company = None
if self.names and len(cnpj) == 14:
@@ -895,7 +945,7 @@ class TinyOrders:
logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s',
contact_id, exc)
return None
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None
return seller_id({'vendedor': {'id': seller}})
def find(self, payload, days=SEARCH_DAYS):
"""An order a previous delivery already created, or None."""

View File

@@ -11,6 +11,9 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account.
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 vendedores [--desde 2026-11-27]
every order sent to Tiny since then, sorted by why its
seller is what it is (read-only; slow, a few calls each)
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
@@ -35,7 +38,7 @@ import json
import os
import sys
import time
from datetime import datetime
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from .core.pricing import PRICES
@@ -169,13 +172,15 @@ def vendedor(orders, numero, out):
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'))}")
full = orders.contact_detail(entry['id']) or entry
situacao = {'A': 'ativo', 'I': 'inativo', 'E': 'excluído'}.get(full.get('situacao'), full.get('situacao') or '?')
out(f" id {entry['id']} · {situacao} · vendedor {seller_label(full.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.')
out(f'Conclusão: hoje a integração escolhe outro contato (id {found}), não o do pedido (id {contact_id}).')
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 ... '
@@ -185,6 +190,84 @@ def vendedor(orders, numero, out):
return True
SELLER_RULE_SINCE = date(2026, 11, 27) # ffc7d31: the registration's seller goes with the order
SELLER_CASES = (
('excluido', 'ligado a um contato excluído ou duplicado sem vendedor, havendo um ativo com vendedor '
'(o erro do #237, corrigido)'),
('enviado', 'contato do pedido com vendedor no cadastro: a integração o enviou'),
('montador', 'cliente sem vendedor no cadastro; Venda do Kanban com o vendedor de quem montou'),
('sem', 'cliente sem vendedor em nenhum cadastro: foi sem vendedor, pela regra'),
('diferentes', 'cadastros ativos com vendedores diferentes'),
('erro', 'não foi possível ler no Tiny'),
)
def patient(call, wait=time.sleep):
"""A report of many calls waits out Tiny's rate limit instead of stopping."""
for attempt in range(8):
try:
return call()
except tiny.TinyRateLimit:
if attempt == 7:
raise
wait(15)
def seller_case(orders, row, choices, wait=time.sleep):
"""(case, the order's seller in Tiny today) for one sent order."""
detail = patient(lambda: orders.request('GET', f"/pedidos/{row['tiny_id']}"), wait)
today = seller_label(detail.get('vendedor'))
linked = (detail.get('cliente') or {}).get('id')
document = tiny.digits(row['document'])
if document not in choices:
choices[document] = patient(lambda: orders.contact_choice(document), wait)
chosen, sellers = choices[document]
if len(sellers) > 1:
return 'diferentes', today
contact = (patient(lambda: orders.contact_detail(linked), wait) or {}) if linked else {}
if tiny.seller_id(contact) and contact.get('situacao') != 'E':
return 'enviado', today
if sellers and (contact.get('situacao') == 'E' or chosen != linked):
return 'excluido', today
if (row.get('assembler') or {}).get('id'):
return 'montador', today
return 'sem', today
def vendedores(orders, rows, out, wait=time.sleep):
"""Every order sent to Tiny, sorted by why its seller is what it is."""
found = {case: [] for case, _ in SELLER_CASES}
choices = {}
for row in rows:
try:
case, today = seller_case(orders, row, choices, wait)
except tiny.TinyError as exc:
case, today = 'erro', str(exc)[:80]
found[case].append(f"#{row['number']} · Tiny {row.get('tiny_number') or row['tiny_id']} · "
f"vendedor no pedido hoje: {today}")
out(f'Pedidos enviados ao Tiny: {len(rows)}')
for case, label in SELLER_CASES:
if found[case]:
out(f'{len(found[case])} {label}:')
for line in found[case]:
out(' ' + line)
return found
def sent_orders(since, connect=None):
"""The orders whose sale reached Tiny since `since`, with the Tiny id."""
if connect is None:
from .core.db import connect
with connect() as c:
return c.execute("""SELECT o.number, o.snapshot->'customer'->>'cnpj' AS document,
o.snapshot->'seller' AS assembler, x.receipt->>'tiny_id' AS tiny_id,
x.receipt->>'tiny_number' AS tiny_number
FROM dtf_local.orders o JOIN dtf_local.outbox x
ON x.event_key = o.id::text || ':paid:tiny' AND x.delivered_at IS NOT NULL
WHERE o.created_at >= %s AND o.parent_id IS NULL AND x.receipt->>'tiny_id' IS NOT NULL
ORDER BY o.number""", (since,)).fetchall()
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)]
@@ -396,7 +479,7 @@ def cancelar(orders, tiny_id, out):
return False
def main(argv=None, orders=None, out=print):
def main(argv=None, orders=None, out=print, rows=None):
parser = argparse.ArgumentParser(prog='python -m app.tiny_probe')
commands = parser.add_subparsers(dest='command', required=True)
listing = commands.add_parser('produtos')
@@ -407,6 +490,8 @@ def main(argv=None, orders=None, out=print):
commands.add_parser('campos')
example = commands.add_parser('exemplo')
example.add_argument('numero')
report = commands.add_parser('vendedores')
report.add_argument('--desde', type=date.fromisoformat, default=SELLER_RULE_SINCE)
seller = commands.add_parser('vendedor')
seller.add_argument('numero')
cancel = commands.add_parser('cancelar')
@@ -440,6 +525,9 @@ 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 == 'vendedores':
vendedores(orders, sent_orders(args.desde) if rows is None else rows, out)
return 0
if args.command == 'vendedor':
return 0 if vendedor(orders, args.numero, out) else 1
if args.command == 'exemplo':

View File

@@ -254,6 +254,44 @@ class TinyTests(FakeTinyCase):
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
def test_a_deleted_duplicate_is_never_used(self):
# #237 (Marcus, 2026-12-02): Tiny listed a deleted Vaneska without a
# seller first; the active one has Kedma.
self.contacts.append({'id': 760864611, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'E'})
self.contacts.append({'id': 760800822, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'A',
'vendedor': {'id': 977226210, 'nome': 'Kedma da Silva'}})
receipt = self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders[0]['idContato'], 760800822)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977226210})
self.assertEqual(receipt['seller'], 977226210)
def test_an_active_contact_with_a_seller_comes_first(self):
self.contacts.append({'id': 400, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'I',
'vendedor': {'id': 7, 'nome': 'Inativo'}})
self.contacts.append({'id': 401, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'A'})
self.contacts.append({'id': 402, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'A',
'vendedor': {'id': 977226210, 'nome': 'Kedma'}})
self.assertEqual(self.tiny.find_contact('11222333000181'), 402)
# Only inactive and seller-less ones: the active one, without a seller.
self.contacts[:] = [c for c in self.contacts if c['id'] != 402]
self.contacts[0]['vendedor'] = None
self.assertEqual(self.tiny.find_contact('11222333000181'), 401)
def test_live_duplicates_with_different_sellers_go_without_and_reach_sentry(self):
self.contacts.append({'id': 500, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'A', 'vendedor': {'id': 7}})
self.contacts.append({'id': 501, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'A', 'vendedor': {'id': 8}})
with self.assertLogs(level='ERROR') as logged:
receipt = self.tiny.deliver('k1', PAID)
self.assertNotIn('vendedor', self.orders[0])
self.assertIsNone(receipt['seller'])
self.assertIn('different sellers', logged.output[0])
def test_only_a_deleted_contact_makes_a_new_one(self):
self.contacts.append({'id': 600, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'E', 'vendedor': {'id': 7}})
self.tiny.deliver('k1', PAID)
self.assertNotEqual(self.orders[0]['idContato'], 600)
self.assertNotIn('vendedor', self.orders[0])
def test_the_registration_seller_wins_over_who_assembled_a_venda(self):
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Kedma'}}}
@@ -923,11 +961,37 @@ class TinyProbeTests(FakeTinyCase):
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'})
# #237: the order went to a deleted duplicate, listed first.
self.contacts.insert(0, {'id': 320, 'cpfCnpj': '11.222.333/0001-81', 'situacao': 'E'})
order['cliente'] = {'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)
self.assertIn('id 320 · excluído · vendedor nenhum', text)
self.assertIn('Conclusão: hoje a integração escolhe outro contato (id 321), não o do pedido (id 320).', text)
def test_vendedores_sorts_every_sent_order_by_why(self):
document = '11.222.333/0001-81'
self.contacts += [{'id': 320, 'cpfCnpj': document, 'situacao': 'E'},
{'id': 321, 'cpfCnpj': document, 'situacao': 'A', 'vendedor': {'id': 977226210, 'nome': 'Kedma'}},
{'id': 330, 'cpfCnpj': '22.333.444/0001-81', 'situacao': 'A'}]
def order(contact, number):
self.orders.append({'id': 9100 + number, 'numeroPedido': str(number), 'cliente': {'id': contact}})
return {'number': number, 'tiny_id': 9100 + number, 'tiny_number': str(number)}
rows = [{**order(320, 1), 'document': document}, # #237: a deleted duplicate
{**order(321, 2), 'document': document}, # the active one with Kedma
{**order(330, 3), 'document': '22.333.444/0001-81', 'assembler': {'id': 2001}},
{**order(330, 4), 'document': '22.333.444/0001-81'}]
from app import tiny_probe
lines = []
tiny_probe.main(['vendedores'], orders=self.tiny, out=lines.append, rows=rows)
text = '\n'.join(lines)
self.assertIn('Pedidos enviados ao Tiny: 4', text)
self.assertIn('1 ligado a um contato excluído', text)
self.assertIn('#1 · Tiny 1 · vendedor no pedido hoje: nenhum', text)
self.assertIn('1 contato do pedido com vendedor no cadastro', text)
self.assertIn('1 cliente sem vendedor no cadastro; Venda do Kanban', text)
self.assertIn('1 cliente sem vendedor em nenhum cadastro', text)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_cancelar_touches_only_test_orders(self):
self.tiny.deliver('k1', PAID)