fix: Tiny uses Dropstar's SKUs and finds the pickup method without settings
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 3m40s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m4s

"Testar conexão" in production said every product and the pickup forma de
envio were "sem id": the SKUs and the pickup id only existed as stack
settings nobody had set. They are Dropstar's fixed catalogue, checked against
its Tiny export: Têxtil as DTFIMP.TX.100CM plus DTFIMP.TX.0010CM to 0090CM,
UV as DTFIMP.UV.1MT plus DTFIMP.UV.010CM, for the ready sheet and loose
artwork alike. These are now the defaults, and the pickup forma de envio is
the one named like "retirar" in Tiny; the test says so when there is none,
or more than one. The settings still override both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-14 11:17:24 -03:00
parent 3c9f05041e
commit 44458aea3e
4 changed files with 102 additions and 15 deletions

View File

@@ -55,6 +55,13 @@ STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
# loose artwork alike. The settings above only override these.
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'}
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
'uvfile': 'DTF UV 28,5 cm · folha montada',
@@ -72,9 +79,11 @@ SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7
# designer message for DTFIMP products on "Aprovado", setting it would reach
# Site customers.
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
# The id of the client's custom "retirar pessoalmente" forma de envio (v2 code
# X), which the pickup notice is keyed on. Find it with the console tool.
# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
# the pickup notice is keyed on. Found in Tiny by name; this setting, an id,
# only overrides that.
PICKUP_SETTING = 'TINY_FORMA_ENVIO_RETIRADA'
PICKUP_NAME = 'retir'
STATE_MINUTES = 10
# Renewal runs about every four hours against a one-day refresh token, so
# less than this left means renewals have been failing for hours.
@@ -110,17 +119,25 @@ def required_settings():
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
# The stack passes every setting, empty when unset, so empty means "the
# default". A setting given for a mode replaces its default, in either form.
def setting(name):
return os.environ.get(name, '').strip()
def sku_prefix(mode):
return os.environ.get(SKU_SETTINGS[mode], '').strip()
return setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, ''))
def step_sku(mode):
return os.environ.get(STEP_SETTINGS[mode], '').strip()
return setting(STEP_SETTINGS[mode]) or ('' if setting(SKU_SETTINGS[mode]) else STEP_DEFAULTS.get(mode, ''))
def metre_sku(mode):
"""The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone."""
return os.environ.get(METRE_SETTINGS[mode], '').strip() if step_sku(mode) else ''
if not step_sku(mode):
return ''
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
def mode_codes(mode):
@@ -363,7 +380,7 @@ def address(destination):
'uf': destination['state'], 'pais': 'Brasil'}
def order_payload(payload, contact_id, today=None, product_id=None):
def order_payload(payload, contact_id, today=None, product_id=None, pickup_id=None):
"""The v3 'pedido' for a paid order's approved snapshot. product_id finds a
SKU's product id by its code, for the modes sold by SKU."""
order = payload['order']
@@ -399,7 +416,8 @@ def order_payload(payload, contact_id, today=None, product_id=None):
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"}
pickup_method = os.environ.get(PICKUP_SETTING, '')
if pickup and pickup_method.isdigit():
pickup_method = int(pickup_method) if pickup_method.isdigit() else pickup_id
if pickup and pickup_method:
pedido['transportador'] = {'formaEnvio': {'id': int(pickup_method)}}
destination = order.get('destination')
if destination:
@@ -435,17 +453,29 @@ def configured_skus(orders, mode):
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
def find_pickup(orders):
"""The one forma de envio named like "retirar", or why there is not one."""
found = orders.request('GET', '/formas-envio', params={'nome': PICKUP_NAME, 'limit': 100}).get('itens') or []
named = [f for f in found if PICKUP_NAME in str(f.get('nome', '')).lower()]
if len(named) == 1:
return named[0], 'ok'
if not named:
return None, 'nenhuma forma de envio com "retir" no nome no Tiny'
return None, 'mais de uma forma de envio com "retir" no nome: ' + ', '.join(
f"{f.get('nome')} ({f.get('id')})" for f in named) + f'; escolha uma em {PICKUP_SETTING}'
def configured_pickup(orders):
"""The forma de envio the pickup setting points at, or why it cannot be used."""
"""The forma de envio used for pickup orders, or why there is none."""
value = os.environ.get(PICKUP_SETTING, '')
if not value.isdigit():
return None, f'{PICKUP_SETTING} sem id'
return orders.request('GET', f'/formas-envio/{value}'), 'ok'
if value.isdigit():
return orders.request('GET', f'/formas-envio/{value}'), 'ok'
return find_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 configured product found active and the pickup
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."""
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
@@ -483,6 +513,7 @@ class TinyOrders:
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
self.today = today
self.skus = {}
self.pickup = None
# The company's names by CNPJ, for new contacts (app.cnpj.company).
self.names = names
@@ -495,6 +526,14 @@ class TinyOrders:
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
return response.json() if response.content else {}
def pickup_id(self):
"""The pickup forma de envio's id, looked up once; None when Tiny has no
single one (the order still goes, without it)."""
if self.pickup is None:
found, _ = configured_pickup(self)
self.pickup = (found or {}).get('id') or 0
return self.pickup or None
def product_id(self, code):
"""The id of the active product with this SKU code, remembered once found."""
if code not in self.skus:
@@ -559,8 +598,10 @@ class TinyOrders:
tiny_id, situacao = existing.get('id'), existing.get('situacao')
else:
contact_id = self.contact(payload['order'])
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today,
product_id=self.product_id))
pickup = (payload['order'].get('freight') or {}).get('service') == 'pickup'
created = self.request('POST', '/pedidos', json=order_payload(
payload, contact_id, self.today, product_id=self.product_id,
pickup_id=self.pickup_id() if pickup else None))
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
tiny_id, situacao = created.get('id'), ABERTA

View File

@@ -104,7 +104,8 @@ def pedido(orders, payload, confirm, out, wait=time.sleep):
out(f"Contato {cnpj}: " + (f"já existe no Tiny (id {known[0]['id']})" if known
else 'não existe; será criado com o e-mail como nome'))
out('Pedido que será enviado:')
out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id),
out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id,
pickup_id=orders.pickup_id()),
ensure_ascii=False, indent=2))
if not confirm:
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')