feat: Boleto with its bank account and Ajuste Fino by SKU in Tiny (Marcus, 12/11)

A faturado montador order's installments carry the bank account set in
TINY_BOLETO_ACCOUNT as their meioPagamento (Tiny v3 parcelas[]), so Tiny
does not pick another account. The Ajuste Fino line resolves the product
from its code (TINY_SKU_TREATMENT, default DTFIMP.AJF.UN) unless a numeric
TINY_PRODUCT_TREATMENT is set; the connection check verifies it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-12 10:52:46 -03:00
parent 5ca6792221
commit 973cd87b36
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: