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

@@ -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':