"""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 pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3] show the test order; --confirmar creates it 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. Cancel the test order in Olist afterwards. """ import argparse import json import sys import time from datetime import datetime from decimal import Decimal, InvalidOperation from .core.pricing import TIERS 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 = TIERS[mode][0][1] 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 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()) 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'] contacts = orders.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5}).get('itens') or [] known = [c for c in contacts if ''.join(ch for ch in str(c.get('cpfCnpj') or '') if ch.isdigit()) == cnpj] if known: out(f"Contato {cnpj}: já existe no Tiny (id {known[0]['id']})") 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 {cnpj}: não existe; será criado como "{name}"') out('Pedido que será enviado:') out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id, shipping=orders.shipping), 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']}") 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. Cancele o pedido no Olist.') return False second = orders.deliver('teste-integracao', payload) out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}") passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id'] out(('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.') + f" Cancele o pedido nº {first['tiny_number']} no Olist.") return passed def main(argv=None, orders=None, out=print): 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') 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') 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 == '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).') return 2 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())