Merge Tiny details of 12/11: Boleto account, Ajuste Fino by SKU
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 6m53s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m15s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-12 11:09:11 -03:00
6 changed files with 129 additions and 34 deletions

View File

@@ -51,9 +51,6 @@ from urllib.parse import urlencode
import httpx
from . import catalog
from .core import db
API = 'https://api.tiny.com.br/public-api/v3'
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
@@ -82,6 +79,13 @@ METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_MET
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'}
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
# Ajuste Fino and Redesenho are sold per art by their own SKUs (Marcus,
# 2026-11-12). TINY_PRODUCT_TREATMENT, a numeric id, still replaces the
# treatment SKU; the Redesenho front will use its SKU later.
TREATMENT_SKU_SETTING = 'TINY_SKU_TREATMENT'
TREATMENT_SKU_DEFAULT = 'DTFIMP.AJF.UN'
REDESIGN_SKU_SETTING = 'TINY_SKU_REDESIGN'
REDESIGN_SKU_DEFAULT = 'DTFIMP.AJF.RED'
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
'uvfile': 'DTF UV 27 cm · folha montada',
@@ -189,15 +193,8 @@ def configured():
def required_settings():
"""The OAuth application, and a product id for each mode not sold by SKU."""
required = ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
# A paid treatment is a line of its own: missing, every treated order would
# fail at the Tiny, so ask for it with the rest of the settings.
with db.connect() as c:
treatment = catalog.current(c)['tratamento']
if treatment['enabled'] and treatment['unit_cents'] > 0:
required.append('TINY_PRODUCT_TREATMENT')
return required
# The stack passes every setting, empty when unset, so empty means "the
@@ -221,6 +218,11 @@ def metre_sku(mode):
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
def treatment_sku():
"""The Ajuste Fino SKU, the client's catalogue default when unset."""
return setting(TREATMENT_SKU_SETTING) or TREATMENT_SKU_DEFAULT
def mode_codes(mode):
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
if step_sku(mode):
@@ -537,24 +539,31 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
items.append(line)
continue
setting = PRODUCT_SETTINGS[item['mode']]
product = os.environ.get(setting, '')
product_setting = PRODUCT_SETTINGS[item['mode']]
product = os.environ.get(product_setting, '')
if not product.isdigit():
raise TinyError(f'{setting} must be the Tiny product id')
raise TinyError(f'{product_setting} must be the Tiny product id')
items.append({'produto': {'id': int(product)},
'quantidade': float(Decimal(item['billed_metres'])),
'valorUnitario': money(item['unit_cents']),
'infoAdicional': note})
treatment = order.get('treatment') or {}
if treatment.get('cents'):
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if not setting.isdigit():
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
# Per art (front 1a): the line carries the band unit price and the arts
# as its quantity. An old quote without those keeps one art at its total.
arts = int(treatment.get('arts') or 1)
unit = int(treatment.get('unit_cents') or treatment['cents'])
items.append({'produto': {'id': int(setting)}, 'quantidade': arts,
# The numeric product id the client gave still wins; otherwise the SKU
# Marcus registered is resolved in the catalogue.
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if legacy.isdigit():
product = int(legacy)
else:
code = treatment_sku()
if product_id is None:
raise TinyError(f'{TREATMENT_SKU_SETTING} needs the SKUs looked up in Tiny')
product = product_id(code)
items.append({'produto': {'id': product}, 'quantidade': arts,
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +24 h'})
@@ -583,12 +592,18 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
method = (payload.get('payment') or {}).get('method')
received = RECEIPT_METHODS.get(method)
if received:
total = money(order['total_cents'])
pedido['pagamento'].update({'formaRecebimento': {'id': received},
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
'formaRecebimento': {'id': received}}]})
parcela = {'dias': 0, 'data': day.isoformat(), 'valor': total,
'formaRecebimento': {'id': received}}
# A boleto installment names its bank account, so Tiny does not pick
# its preferred one ("NEXSTAR COBRANÇA", Marcus 2026-11-12).
account = setting('TINY_BOLETO_ACCOUNT')
if method == 'faturado' and account.isdigit():
parcela['meioPagamento'] = {'id': int(account)}
pedido['pagamento'].update({'formaRecebimento': {'id': received}, 'parcelas': [parcela]})
destination = order.get('destination')
if destination:
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
@@ -625,6 +640,19 @@ def configured_skus(orders, mode):
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
def configured_treatment(orders):
"""Whether Ajuste Fino's product is active: the numeric id when the client
gave one, else the SKU from the catalogue."""
value = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if value.isdigit():
found = orders.request('GET', f'/produtos/{value}')
if found.get('situacao') != 'A':
return f"produto {value} não está ativo no Tiny ({found.get('situacao')})"
return 'ok'
orders.product_id(treatment_sku())
return 'ok'
def find_pickup(orders):
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
named like "retirar", or why there is not one."""
@@ -689,9 +717,9 @@ def configured_pickup(orders):
def check(auth=None, transport=None, orders=None):
"""Read-only proof that the connection and permissions work: one order and
one contact listed, each product's SKUs found active and the pickup
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
otherwise reports each read separately."""
one contact listed, each product's SKUs (and Ajuste Fino) found active and
the pickup forma de envio found, nothing created. Raises TinyNotConnected
when there is no usable connection; otherwise reports each read separately."""
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
def listed(path, **filters):
@@ -704,6 +732,7 @@ def check(auth=None, transport=None, orders=None):
reads = [('pedidos', lambda: listed('/pedidos', dataInicial=since)), ('contatos', lambda: listed('/contatos'))]
reads += [(PRODUCTS[mode], lambda mode=mode: configured_skus(orders, mode) if mode_codes(mode)
else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
reads.append(('Ajuste Fino', lambda: configured_treatment(orders)))
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
results = {}
for name, read in reads:

View File

@@ -30,6 +30,7 @@ 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 datetime
@@ -165,6 +166,15 @@ def conferir(orders, out):
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'):

View File

@@ -53,6 +53,8 @@ TINY_FORMA_ENVIO_RETIRADA=TBD
TINY_STATUS_UPDATES=false
# Tiny id of the forma de recebimento "Boleto" (montador Venda orders).
TINY_RECEIPT_BOLETO=
# Tiny id of the bank account each boleto installment names ("NEXSTAR COBRANÇA").
TINY_BOLETO_ACCOUNT=
# E-mail (password recovery and team alerts). off until the SMTP account exists.
MAIL_ADAPTER=off
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>

View File

@@ -107,6 +107,10 @@ x-app-environment: &app-environment
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
# Ajuste Fino and Redesenho, per art, as the client's SKUs. The numeric
# TINY_PRODUCT_TREATMENT above, when set, still replaces the treatment SKU.
TINY_SKU_TREATMENT: ${TINY_SKU_TREATMENT:-}
TINY_SKU_REDESIGN: ${TINY_SKU_REDESIGN:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
@@ -127,6 +131,9 @@ x-app-environment: &app-environment
# The Tiny forma de recebimento id of "Boleto", for invoiced montador Venda
# orders (front 7a.3). Empty: the order goes without one and its note says so.
TINY_RECEIPT_BOLETO: ${TINY_RECEIPT_BOLETO:-}
# The bank account every boleto installment names ("NEXSTAR COBRANÇA"), so
# Tiny does not pick its preferred one. Empty: no account is sent.
TINY_BOLETO_ACCOUNT: ${TINY_BOLETO_ACCOUNT:-}
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
# only together with TINY_ADAPTER=tiny and after n8n stops sending the

View File

@@ -210,6 +210,9 @@ opens by hand (CDR, AI, PSD, TIFF). The default is 200, R$ 2,00 a metro
Change it only on the client's instruction; the Site shows the new price after
the redeploy.
`TINY_SKU_TREATMENT` is the Ajuste Fino SKU (default `DTFIMP.AJF.UN`);
`TINY_BOLETO_ACCOUNT` is the bank account each boleto installment names.
## 8. Correios
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access

View File

@@ -61,6 +61,9 @@ class FakeTinyCase(unittest.TestCase):
'formasFrete': [{'id': 801, 'nome': '.PACKAGE', 'codigo': '3'}]}}
self.products = {value: {'id': int(value), 'sku': f'DTF-{value}', 'descricao': f'Produto {value}',
'situacao': 'A', 'precos': {'preco': 14.9}} for value in PRODUCTS.values()}
# Ajuste Fino, per art: the SKU Marcus registered (2026-11-12).
self.products['106'] = {'id': 106, 'sku': 'DTFIMP.AJF.UN', 'descricao': 'Ajuste Fino',
'situacao': 'A', 'precos': {'preco': 6.9}}
def handler(request):
path = request.url.path.removeprefix('/public-api/v3')
@@ -157,9 +160,11 @@ class TinyTests(FakeTinyCase):
treatment = {'order': {**base, 'treatment': {'cents': 990, 'hours': 24},
'total_cents': base['total_cents'] + 990},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
# Ajuste Fino is sold by the SKU Marcus registered, found in the
# catalogue: the arts are its quantity and the band its unit price.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(treatment, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
# Per art: the quantity is the number of arts and the unit is the band price.
@@ -167,10 +172,48 @@ class TinyTests(FakeTinyCase):
'unit_cents': 690},
'total_cents': base['total_cents'] + 2070},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(per_art, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# The numeric id, when the client gives one, still wins.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(per_art, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# Without the numeric id, the catalogue lookup is required before sending.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
with self.assertRaisesRegex(TinyError, 'TINY_SKU_TREATMENT'):
order_payload(treatment, 777, date(2026, 9, 24))
def test_faturado_boleto_carries_its_bank_account_on_the_installment(self):
boleto = {'TINY_RECEIPT_BOLETO': '919478947'}
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': '977344551'}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertEqual(pedido['pagamento']['formaRecebimento'], {'id': 919478947})
# Every installment names the account: Tiny must not choose its preferred one.
self.assertEqual(pedido['pagamento']['parcelas'], [{
'dias': 0, 'data': '2026-09-24', 'valor': 84.72,
'formaRecebimento': {'id': 919478947}, 'meioPagamento': {'id': 977344551}}])
self.assertIn('faturado (Boleto)', pedido['observacoesInternas'])
# Without the account setting, no account is sent at all.
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': ''}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
# A pix order never gets the boleto account.
with mock.patch.dict(os.environ, {'TINY_BOLETO_ACCOUNT': '977344551'}):
pedido = order_payload({**PAID, 'payment': {'method': 'pix'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
def test_the_check_lists_ajuste_fino_by_its_sku(self):
from app.tiny import check
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertEqual(check(orders=self.tiny)['Ajuste Fino'], 'ok')
self.products['106']['situacao'] = 'I'
self.tiny.skus.clear()
self.assertIn('DTFIMP.AJF.UN', check(orders=self.tiny)['Ajuste Fino'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)
@@ -231,7 +274,7 @@ class TinyTests(FakeTinyCase):
from app.tiny import check
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
self.assertEqual(set(results.values()), {'ok'})
self.assertEqual(len(results), 8)
self.assertEqual(len(results), 9)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
self.products['103']['situacao'] = 'I'
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
@@ -602,6 +645,7 @@ class TinyProbeTests(FakeTinyCase):
code, text = self.probe('conferir')
self.assertEqual(code, 0)
self.assertIn('TINY_PRODUCT_UV_AVULSA (DTF UV 27 cm · artes avulsas): ok DTF-104', text)
self.assertIn('TINY_SKU_TREATMENT (Ajuste Fino): ok DTFIMP.AJF.UN', text)
self.assertIn('TINY_FORMA_ENVIO_RETIRADA (retirada): ok Retirar pessoalmente', text)
code, text = self.probe('formas-envio')
self.assertIn('77\t6\tRetirar pessoalmente', text)
@@ -815,14 +859,14 @@ class DefaultSkuTests(unittest.TestCase):
class TreatmentSettingTests(unittest.TestCase):
"""A paid treatment needs its own Tiny product, asked with the rest."""
"""Ajuste Fino is sold by its SKU, so no product id is required any more."""
def test_the_treatment_product_is_required_only_when_it_is_paid(self):
def test_the_treatment_id_is_never_required(self):
from app.tiny import required_settings
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '0'}):
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TINY_SKU_TREATMENT': 'DTFIMP.AJF.LOTE'}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '5000'}):
self.assertIn('TINY_PRODUCT_TREATMENT', required_settings())
if __name__ == '__main__':