Files
dtf-system/app/tiny_probe.py
Cauê Faleiros f23b64bebf
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
fix: a Tiny order goes to the customer's live contact, never a deleted one, and takes its seller (Marcus, 2026-12-02, #237)
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>
2026-12-02 16:23:47 -03:00

561 lines
28 KiB
Python

"""Supervised checks against the client's real Tiny, run by hand from a
container console (docker exec, or Portainer > Containers > worker > Console).
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 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
python -m app.tiny_probe usuarios the account's users and their type, and which one the
integration is connected as (read-only; needs the app's
Usuários (Leitura) and a reconnect)
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
be found by its purchase-order number) and only then by a second delivery,
which must return the existing order. If the search cannot find the order, the
second delivery is not attempted: it would create a duplicate. Either way the
test order is then cancelled through the API (Tiny has no delete, and the
team's users may not cancel by hand), and read back to show it is.
"""
import argparse
import base64
import json
import os
import sys
import time
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from .core.pricing import PRICES
from .core.secrets import load as load_secret_files
from . import tiny
FIND_ATTEMPTS = 4
FIND_WAIT_SECONDS = 5
def test_order(cnpj, email, celular, mode, now=None, metres='1'):
number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
unit = PRICES[mode]
total = int(Decimal(metres) * unit)
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': unit,
'total_cents': total}],
'freight': {'service': 'pickup', 'total_cents': 0},
'destination': None, 'total_cents': total}}
def produtos(orders, termo, out):
params = {'situacao': 'A', 'limit': 100}
if termo:
params['nome'] = termo
found = orders.request('GET', '/produtos', params=params).get('itens') or []
for item in found:
preco = (item.get('precos') or {}).get('preco')
out(f"{item['id']}\t{item.get('sku') or '-'}\t{item.get('descricao')}\tR$ {preco}")
out(f'{len(found)} produto(s) ativo(s)' + (f' com "{termo}"' if termo else '') + '.')
def formas_envio(orders, termo, out):
params = {'limit': 100}
if termo:
params['nome'] = termo
found = orders.request('GET', '/formas-envio', params=params).get('itens') or []
for item in found:
out(f"{item.get('id')}\t{item.get('tipo')}\t{item.get('nome')}")
out(f'{len(found)} forma(s) de envio' + (f' com "{termo}"' if termo else '') +
'. 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. ({exc})' 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 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:
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(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 ... '
'--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
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)]
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():
prefix, step = tiny.sku_prefix(mode), tiny.step_sku(mode)
if step:
result = tiny.configured_skus(orders, mode)
ok &= result == 'ok'
metre = tiny.metre_sku(mode)
out(f'{tiny.STEP_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
f'({metre + " por metro e " if metre else ""}{step} a cada 10 cm)')
continue
if prefix:
result = tiny.configured_skus(orders, mode)
ok &= result == 'ok'
out(f'{tiny.SKU_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
f'({prefix}.100CM e {prefix}.0010CM a {prefix}.0090CM)')
continue
product, result = tiny.configured_product(orders, mode)
ok &= result == 'ok'
described = f"{product.get('sku') or '-'} · {product.get('descricao')}" if product else ''
out(f'{setting} ({tiny.PRODUCTS[mode]}): {result} {described}'.rstrip())
method, result = tiny.configured_pickup(orders)
ok &= result == 'ok'
out(f"{tiny.PICKUP_SETTING} (retirada): {result} {method.get('nome') if method else ''}".rstrip())
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '').strip()
try:
result = tiny.configured_treatment(orders)
except tiny.TinyError as exc:
result = str(exc)[:200]
ok &= result == 'ok'
label = 'TINY_PRODUCT_TREATMENT' if legacy.isdigit() else tiny.TREATMENT_SKU_SETTING
code = legacy if legacy.isdigit() else tiny.treatment_sku()
out(f'{label} (Ajuste Fino): {result} {code}'.rstrip())
out(f"{tiny.STATUS_UPDATES_SETTING}: {'ligado' if tiny.status_updates() else 'desligado'}")
for name, result in tiny.check(orders=orders).items():
if name in ('pedidos', 'contatos'):
ok &= result == 'ok'
out(f'{name}: {result}')
out('Tudo conferido.' if ok else 'Há pendências acima.')
return ok
def pedido(orders, payload, confirm, out, wait=time.sleep):
cnpj = payload['order']['customer']['cnpj']
known = orders.find_contact(cnpj)
if known:
out(f"Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})")
else:
# Named as the worker names a new customer: the company in the CNPJ registry.
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, contact_seller=seller),
ensure_ascii=False, indent=2))
out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)')
if not confirm:
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')
return None
first = orders.deliver('teste-integracao', payload)
out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}")
try:
for attempt in range(FIND_ATTEMPTS):
found = orders.find(payload)
if found:
break
if attempt < FIND_ATTEMPTS - 1:
wait(FIND_WAIT_SECONDS)
else:
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
'Um reenvio criaria um duplicado; o 2º envio não foi feito.')
return False
# What Tiny kept of the e-commerce number, read back from the order.
wanted = tiny.purchase_order(payload['number'])
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.')
second = orders.deliver('teste-integracao', payload)
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 and seller_kept
finally:
# Whatever happened above, the test order does not stay open.
cancelar(orders, first['tiny_id'], out)
def connected_as(orders):
"""Who logged in when the integration was connected: the name and e-mail
in the access token's claims (an OpenID token), never the token itself."""
try:
part = orders.auth.access_token().split('.')[1]
claims = json.loads(base64.urlsafe_b64decode(part + '=' * (-len(part) % 4)))
except Exception:
return {}
return {key: claims[key] for key in ('name', 'email', 'preferred_username') if claims.get(key)}
def usuarios(orders, out):
"""The account's users, with their type, and the one the integration
acts as: the API does what that user may do (read-only)."""
me = connected_as(orders)
if me:
out('Integração conectada como: ' + ' · '.join(str(v) for v in me.values()))
try:
found = orders.request('GET', '/usuarios', params={'limit': 100}).get('itens') or []
except tiny.TinyError as exc:
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
out(f'Tiny recusou a lista de usuários ({exc}). Marque Usuários (Leitura) nas permissões do '
'aplicativo e conecte o Tiny de novo no Kanban (Integrações).')
return False
raise
ours = {str(v).lower() for v in me.values()}
for user in found:
mine = str(user.get('email') or '').lower() in ours or str(user.get('emailComunicacao') or '').lower() in ours
out(f"{user.get('id')}\t{user.get('tipo') or '-'}\t{user.get('nome')}\t{user.get('email')}"
+ ('\t<- integração' if mine else ''))
out(f'{len(found)} usuário(s).')
return True
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."""
try:
detail = orders.request('GET', f'/pedidos/{tiny_id}')
number = detail.get('numeroPedido')
if not str(detail.get('numeroOrdemCompra') or '').startswith(tiny.purchase_order('TESTE-')):
out(f'Recusado: o pedido {tiny_id} não é um pedido de teste (DTF-TESTE-...); nada foi alterado.')
return False
if detail.get('situacao') != tiny.CANCELADA:
orders.set_situacao(tiny_id, tiny.CANCELADA)
detail = orders.request('GET', f'/pedidos/{tiny_id}')
except tiny.TinyError as exc:
out(f'FALHA ao cancelar o pedido {tiny_id}: {exc}. Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
situacao = detail.get('situacao')
if situacao == tiny.CANCELADA:
out(f'Pedido nº {number} cancelado no Tiny.')
return True
out(f'FALHA: o pedido nº {number} ficou em {tiny.SITUACOES.get(situacao, situacao)}. '
f'Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
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')
listing.add_argument('termo', nargs='?', default='')
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')
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')
cancel.add_argument('tiny_id', type=int)
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)
order.add_argument('--celular', required=True)
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')
commands.add_parser('usuarios')
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()
from .cnpj import company
# The same names for new contacts as the worker uses (app/worker.py).
orders = tiny.TinyOrders(auth=tiny.TinyAuth(), names=company)
try:
if args.command == 'produtos':
produtos(orders, args.termo, out)
return 0
if args.command == 'formas-envio':
formas_envio(orders, args.termo, out)
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 == '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':
return 0 if exemplo(orders, args.numero, out) else 1
if args.command == 'cancelar':
return 0 if cancelar(orders, args.tiny_id, out) else 1
if args.command == 'usuarios':
return 0 if usuarios(orders, 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).')
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:
metres = Decimal(0)
if metres < 1 or (metres * 10) % 1:
out('Informe a metragem a partir de 1 m, em passos de 10 cm (ex.: 1.3).')
return 2
payload = test_order(cnpj, args.email, args.celular, args.modo, metres=str(metres))
return 0 if pedido(orders, payload, args.confirmar, out) is not False else 1
except tiny.TinyError as exc:
out(f'Tiny: {exc}')
return 1
if __name__ == '__main__':
sys.exit(main())