"""Tiny/Olist ERP (API v3): create the sales order once a payment is approved. Written from the public API documentation and exercised only against a fake HTTP transport. Tiny has no sandbox: the first real test creates a real order in the client's ERP, so test with a marked order and cancel it afterwards. Authentication is OAuth2 on Tiny's Keycloak. The client creates an "Aplicativo" in Tiny (Configurações > Geral > Aplicativos), which yields a client ID and secret and registers our callback URL. An operator then clicks "Conectar Tiny" on the Kanban once; the tokens are kept in the database and the refresh token is rotated on every refresh, under a row lock so two workers never spend the same one. Orders are created by contact and product id: the customer's contact is found by CNPJ or created, and each product mode maps to a product that must already exist in Tiny (PRODUCT_SETTINGS), sold by the metre. A mode can instead be sold as the client's own SKUs per length (SKU_SETTINGS): the order is then a sum, 1,30 m = 1 × "1 metro" + 1 × "30 cm", at the price the customer paid. Idempotency: the outbox may deliver the same event more than once. Every order carries numeroOrdemCompra = "DTF-", and before creating one the customer's recent orders are searched for that number, so a second delivery finds the first order instead of creating another. The same number goes in numeroPedidoEcommerce (Dropstar, 2026-10-23), which n8n reads as numero_ecommerce. Customer notices: the client sends WhatsApp messages from Tiny's order situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of situação, none for Imprimindo, Correção or Revisão): paid (Arte recebida) -> Aprovada (the "approved" notice) Arte conferida (queue) -> Preparando envio (no notice) Finalizado -> Pronto para envio (pickup or delivery) cancelled -> Cancelada (no notice) After Pronto para envio the order goes on in Tiny like any other: Enviada, Entregue. An order someone already moved further in Tiny is never moved back, and an invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny). Pickup orders carry the client's "retirar pessoalmente" forma de envio. """ import os import secrets import time from datetime import datetime, timedelta, timezone from decimal import Decimal from urllib.parse import urlencode import httpx API = 'https://api.tiny.com.br/public-api/v3' AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect' # Not TINY_PRODUCT_: app/core/secrets.py reads any variable ending in # _FILE as a path to a secret file, and one product mode is called "file". PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA', 'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA', 'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'} # The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM, # the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces # the mode's product id. SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA', 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA', 'premium': 'TINY_SKU_TEXTIL_PREMIUM'} # Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after # a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm. STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA', 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA', 'premium': 'TINY_SKU10_TEXTIL_PREMIUM'} 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', 'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'} # 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', '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', 'uv': 'DTF UV 27 cm · artes avulsas', 'premium': 'DTF Têxtil Premium 57 cm · folha montada'} # How far back to look for an order a previous delivery may already have made. SEARCH_DAYS = 7 # A "ready" event can come after corrections; it normally knows the Tiny id. READY_SEARCH_DAYS = 45 # Tiny v3 order situações (PUT /pedidos/{id}/situacao). ABERTA, APROVADA, PRONTO_ENVIO, ENVIADA, ENTREGUE, CANCELADA, NAO_ENTREGUE = 0, 3, 7, 5, 6, 2, 9 PREPARANDO, FATURADA, INCOMPLETA = 4, 1, 8 SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7: 'Pronto para envio', 5: 'Enviada', 6: 'Entregue', 2: 'Cancelada', 8: 'Dados incompletos', 9: 'Não entregue'} # The client's customer notices (Tiny webhook -> middleware -> n8n -> WhatsApp) # react to these situações. Off until go-live: while n8n still sends the # designer message for DTFIMP products on "Aprovado", setting it would reach # Site customers. # Where the order came from (D-21) and, when the team registered it, how it was # paid outside the system (D-35), for whoever reads the order in Tiny. ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'} OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'} def internal_note(payload): paid = payload.get('payment') or {} method = paid.get('method') if method == 'faturado': # A montador Venda order is invoiced (front 7a.3): its forma de # recebimento is "Boleto" when the client's id is configured. boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir' else: how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago' note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" with_order = (payload.get('order') or {}).get('with_order') if with_order: note += f' · junto com o pedido de roupa nº {with_order}' return note STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' # 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' PICKUP_EXACT = 'retirar pessoalmente' # Dropstar's own ids, read from its store orders with app.tiny_probe exemplo # (2026-10-19). The app may not list formas de recebimento, so these are not # looked up: Pix and credit card, as the store's orders are paid, and the # DropStar carrier its pickup orders name. Dinheiro and, for the customer's # credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for # the orders the team registers as paid outside the site (D-35). "Boleto" is # for a montador Venda order (front 7a.3); no id is known yet, and while # TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento. _BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654, **({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})} PICKUP_CARRIER = 761565838 # Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on # 2026-10-26; it goes in pagamento.categoria, and replaced the store's # "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact, # 2026-10-23; a montador Venda carries who assembled it, 2026-11-17), and the marcador SITE DTF, added after the order is created: # POST /pedidos does not take marcadores. Capitals, no accent, no extra # space: the string Kondado reads for Power BI. CATEGORY = 986932924 # Dropflow's orders in their own category, "DTF DROPFLOW" (sent 2026-10-27): # the rules document (D-21) keeps the two channels apart in the financial. CATEGORIES = {'dropflow': 987032506} TAG = 'SITE DTF' # Freight is the sender's (CIF), as on the store's orders. FREIGHT_PAID_BY = 'R' # The forma de envio each delivery service uses, by name; a Correios service # is the forma de frete with its contract code (app/correios.py). CARRIERS = {'pac': 'correios', 'sedex': 'correios', 'jadlog': 'jadlog'} 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. EXPIRY_WARNING = timedelta(hours=12) # Brazil has had no daylight saving since 2019; the order date is the local day. BRASILIA = timezone(timedelta(hours=-3)) def local_today(): return datetime.now(BRASILIA).date() class TinyError(Exception): pass class TinyNotConnected(TinyError): """No authorised connection yet: an operator must click "Conectar Tiny".""" def purchase_order(number): return f'DTF-{number}' def configured(): """Whether the OAuth application is configured (orders may still be fake).""" return all(os.environ.get(name) for name in ('TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI')) def required_settings(): """The OAuth application, and a product id for each mode not sold by SKU.""" 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))] # 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 setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, '')) def step_sku(mode): 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.""" if not step_sku(mode): return '' 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): return [code for code in (metre_sku(mode), step_sku(mode)) if code] return sku_codes(sku_prefix(mode)) if sku_prefix(mode) else [] def sku_codes(prefix): """The metre SKU and the nine of 10 to 90 cm, as the client's catalogue names them.""" return [f'{prefix}.100CM'] + [f'{prefix}.{cm:04d}CM' for cm in range(10, 100, 10)] def tenths(item): """The billed length in 10 cm steps; the Site bills in them.""" billed = Decimal(item['billed_metres']) steps = billed * 10 if steps != steps.to_integral_value(): raise TinyError(f'{billed} m is not a whole number of 10 cm steps') return int(steps), int(billed * int(item['unit_cents'])) def step_lines(item, code, metre=''): """(code, quantity, cents each) for a 10 cm SKU, after whole metres of the metre SKU when there is one, adding up to the item's total; a rest that does not divide goes on one line of its own.""" steps, total = tenths(item) lines = [] if metre and steps >= 10: metres, steps = divmod(steps, 10) unit = int(item['unit_cents']) lines.append((metre, metres, unit)) total -= metres * unit if not steps: return lines return lines + split_steps(code, steps, total) def split_steps(code, steps, total): each, rest = divmod(total, steps) if not rest: return [(code, steps, each)] return [(code, steps - 1, each), (code, 1, each + rest)] if steps > 1 else [(code, 1, total)] def sku_lines(item, prefix): """(code, quantity, cents each) adding up to the item: whole metres as the metre SKU, the rest as one 10 cm SKU. The Site bills in 10 cm steps, so the rest always has a SKU; the lines carry the price the customer paid.""" billed = Decimal(item['billed_metres']) centimetres = billed * 100 if centimetres != centimetres.to_integral_value() or int(centimetres) % 10: raise TinyError(f'{billed} m is not a whole number of 10 cm steps') metres, rest = divmod(int(centimetres), 100) unit = int(item['unit_cents']) lines = [(f'{prefix}.100CM', metres, unit)] if metres else [] if rest: # What is left of the item's total, so the order adds up to the cent. lines.append((f'{prefix}.{rest:04d}CM', 1, int(billed * unit) - metres * unit)) return lines def status_updates(): return os.environ.get(STATUS_UPDATES_SETTING, '').lower() == 'true' # OAuth ------------------------------------------------------------------- class TinyAuth: """The OAuth application and the stored connection.""" def __init__(self, connect=None, transport=None, clock=time.time): self.client_id = os.environ.get('TINY_CLIENT_ID', '') self.client_secret = os.environ.get('TINY_CLIENT_SECRET', '') self.redirect_uri = os.environ.get('TINY_REDIRECT_URI', '') if connect is None: from .core.db import connect self.connect = connect self.http = httpx.Client(timeout=20, transport=transport) self.clock = clock def authorize_url(self, operator, offline=True): """Start a connection. The state is single-use, short-lived, and only an authenticated operator can create one, which is what protects the callback: Tiny's redirect back is cross-site, so the operator's SameSite=Strict cookie does not travel with it. offline_access asks for a grant that is not bound to a login session, so the connection lasts as long as it keeps being renewed. Tiny's documented refresh token otherwise lasts one day.""" state = secrets.token_urlsafe(32) with self.connect() as c: c.execute("DELETE FROM dtf_local.oauth_states WHERE expires_atnow() RETURNING operator''', (state,)).fetchone() if not row: raise TinyError('Unknown or expired authorisation state') return row['operator'] def complete(self, code, state): """Exchange the authorisation code; returns the operator who started it.""" with self.connect() as c: operator = self._claim(c, state) tokens = self._token({'grant_type': 'authorization_code', 'code': code, 'redirect_uri': self.redirect_uri}) self._store(c, tokens, operator) return operator def without_offline(self, state): """Tiny refused the offline_access scope for this application: spend the operator's state and start again with a session-bound grant.""" with self.connect() as c: operator = self._claim(c, state) return self.authorize_url(operator, offline=False) def status(self, c=None): if c is None: with self.connect() as c: return self.status(c) row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline, refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone() if not row: return {'connected': False} now = datetime.now(timezone.utc) expires = row['refresh_expires_at'] expired = bool(expires and expires <= now) if row['refused_at']: problem = 'refused' elif expired: problem = 'expired' elif row['refresh_failed_at']: problem = 'renewal-failing' elif expires and expires - now < EXPIRY_WARNING: problem = 'expiring' else: problem = None return {'connected': not expired and not row['refused_at'], 'problem': problem, 'connected_by': row['connected_by'], 'connected_at': row['connected_at'], 'renewed_at': row['updated_at'], 'expires_at': expires, 'offline': row['offline'], 'failed_at': row['refresh_failed_at']} def access_token(self): """A valid access token, refreshing (and rotating) under a row lock. A failed renewal is recorded after the lock is released, so the Kanban can show it. A refused refresh token is never tried again: only a new connection helps, and retrying it would only repeat the refusal.""" with self.connect() as c: row = c.execute('''SELECT * FROM dtf_local.provider_tokens WHERE provider='tiny' FOR UPDATE''').fetchone() if not row: raise TinyNotConnected('Tiny is not connected; use "Conectar Tiny" on the Kanban') now = datetime.now(timezone.utc) if row['access_expires_at'] > now + timedelta(seconds=60): return row['access_token'] if row['refused_at']: raise TinyNotConnected('Tiny refused the stored refresh token; connect again on the Kanban') if row['refresh_expires_at'] and row['refresh_expires_at'] <= now: raise TinyNotConnected('The Tiny connection expired; connect again on the Kanban') try: tokens = self._token({'grant_type': 'refresh_token', 'refresh_token': row['refresh_token']}) except (TinyError, httpx.HTTPError, ValueError) as exc: failure = exc else: self._store(c, tokens, row['connected_by'], refreshed=True) return tokens['access_token'] # Only against the token that failed: another worker may have renewed since. with self.connect() as c: c.execute('''UPDATE dtf_local.provider_tokens SET refresh_failed_at=now(), refresh_error=%s, refused_at=CASE WHEN %s THEN now() ELSE refused_at END WHERE provider='tiny' AND refresh_token=%s''', (str(failure)[:300] or type(failure).__name__, isinstance(failure, TinyNotConnected), row['refresh_token'])) raise failure def _token(self, form): response = self.http.post(f'{AUTH}/token', data={**form, 'client_id': self.client_id, 'client_secret': self.client_secret}) if response.status_code == 400 and form['grant_type'] == 'refresh_token': raise TinyNotConnected('Tiny refused the stored refresh token; connect again on the Kanban') response.raise_for_status() tokens = response.json() if not tokens.get('access_token') or not tokens.get('refresh_token'): raise TinyError('Tiny token response is missing tokens') return tokens def _store(self, c, tokens, operator, refreshed=False): now = datetime.now(timezone.utc) access_expires = now + timedelta(seconds=int(tokens.get('expires_in', 300))) # An offline grant reports refresh_expires_in 0: no fixed end. refresh_in = tokens.get('refresh_expires_in') refresh_expires = now + timedelta(seconds=int(refresh_in)) if refresh_in else None offline = 'offline_access' in str(tokens.get('scope') or '').split() c.execute('''INSERT INTO dtf_local.provider_tokens(provider,access_token,refresh_token, access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at,offline) VALUES('tiny',%s,%s,%s,%s,%s,now(),now(),%s) ON CONFLICT(provider) DO UPDATE SET access_token=EXCLUDED.access_token, refresh_token=EXCLUDED.refresh_token, access_expires_at=EXCLUDED.access_expires_at, refresh_expires_at=EXCLUDED.refresh_expires_at, updated_at=now(), offline=EXCLUDED.offline, refresh_failed_at=NULL, refresh_error=NULL, refused_at=NULL, connected_by=CASE WHEN %s THEN dtf_local.provider_tokens.connected_by ELSE EXCLUDED.connected_by END, connected_at=CASE WHEN %s THEN dtf_local.provider_tokens.connected_at ELSE now() END''', (tokens['access_token'], tokens['refresh_token'], access_expires, refresh_expires, operator, offline, refreshed, refreshed)) # Orders ------------------------------------------------------------------ def money(cents): return float(Decimal(cents) / 100) def punctuated(document): """A CPF or CNPJ as Tiny keeps it, 130.323.978-71 or 11.222.333/0001-81: its searches match that exact text, so the bare digits find nothing.""" d = ''.join(ch for ch in str(document) if ch.isdigit()) if len(d) == 11: return f'{d[:3]}.{d[3:6]}.{d[6:9]}-{d[9:]}' if len(d) == 14: return f'{d[:2]}.{d[2:5]}.{d[5:8]}/{d[8:12]}-{d[12:]}' return d def search_forms(document): """Punctuated first, as Tiny keeps it; then the bare digits, for a contact someone typed in without punctuation.""" d = ''.join(ch for ch in str(document) if ch.isdigit()) return list(dict.fromkeys((punctuated(d), d))) def list_sellers(orders, pages=10): """Tiny's sellers (vendedores) as [{id, name}], for the Kanban user a Venda's seller comes from (Marcus, 2026-11-17). v3 names the seller on the entry or on its contact; both are read.""" sellers = [] for page in range(pages): found = orders.request('GET', '/vendedores', params={'limit': 100, 'offset': page * 100}) items = found if isinstance(found, list) else (found.get('itens') or []) for entry in items: contact = entry.get('contato') or {} name = entry.get('nome') or contact.get('nome') or contact.get('fantasia') or '' if entry.get('id'): sellers.append({'id': entry['id'], 'name': name or f"Vendedor {entry['id']}"}) if len(items) < 100: break return sorted(sellers, key=lambda s: s['name'].lower()) def search_contacts(orders, query, limit=10): """Up to `limit` contacts matching what was typed (the montador's typeahead, front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by name. Tiny's own search does the matching.""" text = str(query or '').strip() digits = ''.join(ch for ch in text if ch.isdigit()) found = [] if digits and not any(ch.isalpha() for ch in text): for form in search_forms(digits): found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or [] else: found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or [] contacts, seen = [], set() for entry in found: if entry.get('id') in seen: continue seen.add(entry.get('id')) contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '', 'document': entry.get('cpfCnpj') or '', 'email': entry.get('email') or '', 'phone': entry.get('telefone') or entry.get('celular') or ''}) return contacts[:limit] def contact_payload(order, company=None): """A new contact, named after the company's razão social when the registry gave it (app/cnpj.py), else the customer's name, else the recipient or the e-mail. A CPF (11 digits) is a person (F), a CNPJ a company (J).""" customer = order['customer'] destination = order.get('destination') company = company or {} contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient') or customer['mail']), 'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': punctuated(customer['cnpj']), 'email': customer['mail'], 'celular': customer['zap'], 'situacao': 'A'} if company.get('trade'): contact['fantasia'] = company['trade'] if destination: contact['endereco'] = address(destination) return contact def address(destination): return {'endereco': destination['street'], 'numero': destination['number'], 'complemento': destination.get('complement', ''), 'bairro': destination['district'], 'municipio': destination['city'], 'cep': destination['postal_code'], 'uf': destination['state'], 'pais': 'Brasil'} def business_days_after(day, days): """The day `days` working days (Monday to Friday) after `day`.""" while days > 0: day += timedelta(days=1) if day.weekday() < 5: days -= 1 return day def order_payload(payload, contact_id, today=None, product_id=None, shipping=None): """The v3 'pedido' for a paid order's approved snapshot, filled in as the store's own orders are: payment, carrier and expected date. product_id finds a SKU's product id by its code; shipping(service) the forma de envio and de frete of a delivery service or pickup.""" order = payload['order'] items = [] for item in order['items']: note = PRODUCTS[item['mode']] + f" · nota {item['grade']}" prefix, step = sku_prefix(item['mode']), step_sku(item['mode']) if step or prefix: if product_id is None: raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny") lines = step_lines(item, step, metre_sku(item['mode'])) if step else sku_lines(item, prefix) for index, (code, quantity, cents) in enumerate(lines): line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)} if index == 0: line['infoAdicional'] = note + f" · {item['billed_metres']} m" items.append(line) continue product_setting = PRODUCT_SETTINGS[item['mode']] product = os.environ.get(product_setting, '') if not product.isdigit(): 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'): # 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']) # 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'}) redesign = order.get('redesign') or {} if redesign.get('cents'): # Ajuste Fino Redesenho (front 1b): per art, resolved by its SKU code, # one price (never a band), 48 h. Empty setting means the default code. if product_id is None: raise TinyError('TINY_SKU_REDESIGN needs the SKU looked up in Tiny') code = setting(REDESIGN_SKU_SETTING) or REDESIGN_SKU_DEFAULT arts = int(redesign.get('arts') or 1) unit = int(redesign.get('unit_cents') or redesign['cents']) items.append({'produto': {'id': product_id(code)}, 'quantidade': arts, 'valorUnitario': money(unit), 'infoAdicional': 'Ajuste Fino Redesenho · '+str(arts)+ (' arte' if arts == 1 else ' artes')+' · +48 h'}) freight = order['freight'] service = freight.get('service') pickup = service == 'pickup' day = today or local_today() pedido = {'data': day.isoformat(), 'idContato': contact_id, 'numeroOrdemCompra': purchase_order(payload['number']), 'itens': items, 'valorFrete': money(freight['total_cents']), 'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''), 'observacoesInternas': internal_note(payload)} # No seller, so Tiny's channel sets it (Dropstar, 2026-10-23), except a # montador Venda, whose seller is who assembled it (Marcus, 2026-11-17). seller = (order.get('seller') or {}).get('id') if seller: pedido['vendedor'] = {'id': int(seller)} coupon = order.get('coupon') or {} if coupon: # Tiny's v3 order has the order-level discount next to valorFrete. pedido['valorDesconto'] = money(coupon.get('discount_cents') or 0) carrier = shipping(service) if shipping else None if carrier: pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier} # The carrier's time already counts production; a pickup is ready after it. days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0) if days is not None: # Redesenho adds 48 h (two working days); the basic adds one. extra = 2 if redesign.get('cents') else 1 if treatment.get('cents') else 0 days = int(days) + extra 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)}} method = (payload.get('payment') or {}).get('method') received = RECEIPT_METHODS.get(method) if received: total = money(order['total_cents']) 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'], 'nomeDestinatario': destination['recipient']} del pedido['enderecoEntrega']['numero'] # The channel id is optional in Tiny's v3 model; TINY_ECOMMERCE_ID adds it. pedido['ecommerce'] = {'numeroPedidoEcommerce': purchase_order(payload['number'])} ecommerce = os.environ.get('TINY_ECOMMERCE_ID', '') if ecommerce.isdigit(): pedido['ecommerce']['id'] = int(ecommerce) return pedido def configured_product(orders, mode): """The Tiny product a mode's setting points at, or a reason it cannot be used.""" setting = PRODUCT_SETTINGS[mode] value = os.environ.get(setting, '') if not value.isdigit(): return None, f'{setting} sem id' found = orders.request('GET', f'/produtos/{value}') if found.get('situacao') != 'A': return found, f"produto {value} não está ativo no Tiny ({found.get('situacao')})" return found, 'ok' def configured_skus(orders, mode): """Whether every SKU of a mode sold by SKU is an active product in Tiny.""" missing = [] for code in mode_codes(mode): try: orders.product_id(code) except TinyError: missing.append(code) 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.""" 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()] # The account also has "Retirar na loja", unused: the exact name decides. exact = [f for f in named if ' '.join(str(f.get('nome', '')).lower().split()) == PICKUP_EXACT] if len(exact) == 1: return exact[0], 'ok' 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 find_shipping(orders, service): """The forma de envio and de frete for a service, as {'formaEnvio': ..., 'formaFrete': ...} (and the DropStar carrier for pickup), or None when Tiny has no such forma de envio: the order then goes without it.""" if service == 'pickup': method, _ = configured_pickup(orders) if not method: return None detail = orders.request('GET', f"/formas-envio/{method['id']}") options = detail.get('formasFrete') or [] # "Retirar em loja", as the store's pickup orders. frete = next((f for f in options if PICKUP_NAME in str(f.get('nome', '')).lower()), options[0] if options else None) found = {'id': PICKUP_CARRIER, 'formaEnvio': {'id': int(method['id'])}} if frete: found['formaFrete'] = {'id': int(frete['id'])} return found name = CARRIERS.get(service) if not name: return None listed = orders.request('GET', '/formas-envio', params={'nome': name, 'limit': 100}).get('itens') or [] method = next((f for f in listed if str(f.get('nome', '')).strip().lower() == name), None) if not method: return None options = orders.request('GET', f"/formas-envio/{method['id']}").get('formasFrete') or [] if name == 'correios': from .correios import SERVICES setting, default, _ = SERVICES[service] code = (os.environ.get(setting) or default).strip() frete = next((f for f in options if str(f.get('codigo', '')).strip() == code), None) else: frete = options[0] if options else None found = {'formaEnvio': {'id': int(method['id'])}} if frete: found['formaFrete'] = {'id': int(frete['id'])} return found def configured_pickup(orders): """The forma de envio used for pickup orders, or why there is none.""" value = os.environ.get(PICKUP_SETTING, '') 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 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): orders.request('GET', path, params={'limit': 1, **filters}) return 'ok' # Unfiltered, a large account's order list times out ("Sua consulta levou # muito tempo"): yesterday's orders prove the same permission. since = (local_today() - timedelta(days=1)).isoformat() 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: try: results[name] = read() except TinyNotConnected: raise except TinyError as exc: results[name] = str(exc)[:200] except httpx.HTTPError: results[name] = 'sem resposta do Tiny' return results class TinyOrders: def __init__(self, auth=None, transport=None, today=None, names=None): missing = [name for name in required_settings() if not os.environ.get(name)] if auth is None and missing: raise RuntimeError('Tiny needs ' + ', '.join(missing)) self.auth = auth or TinyAuth() self.http = httpx.Client(base_url=API, transport=transport, timeout=30) self.today = today self.skus = {} self.carriers = {} # The company's names by CNPJ, for new contacts (app.cnpj.company). self.names = names def request(self, method, path, **kwargs): headers = {'Authorization': f'Bearer {self.auth.access_token()}'} response = self.http.request(method, path, headers=headers, **kwargs) if response.status_code == 429: raise TinyError('Tiny rate limit reached; the outbox will retry') if response.status_code >= 400: raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') return response.json() if response.content else {} def shipping(self, service): """The forma de envio and de frete of a service, looked up once.""" if service not in self.carriers: self.carriers[service] = find_shipping(self, service) return self.carriers[service] def product_id(self, code): """The id of the active product with this SKU code, remembered once found.""" if code not in self.skus: found = self.request('GET', '/produtos', params={'codigo': code, 'situacao': 'A', 'limit': 10}) # The filter may match more than the exact code: DTFIMP.TX.010CM is # a different product from DTFIMP.TX.0010CM. match = [p for p in found.get('itens') or [] if str(p.get('sku') or p.get('codigo') or '') == code and p.get('situacao', 'A') == 'A'] if not match: raise TinyError(f'SKU {code} não encontrado entre os produtos ativos do Tiny') self.skus[code] = int(match[0]['id']) return self.skus[code] def find_contact(self, cnpj): """The id of the customer's existing contact, or None.""" for form in search_forms(cnpj): found = self.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': 5}) for entry in found.get('itens') or []: if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj: return entry['id'] return None def contact(self, order): cnpj = order['customer']['cnpj'] known = self.find_contact(cnpj) if known: return known company = None if self.names and len(cnpj) == 14: try: company = self.names(cnpj) except Exception: # a name is a nicety; the order must still go company = None return self.request('POST', '/contatos', json=contact_payload(order, company))['id'] def find(self, payload, days=SEARCH_DAYS): """An order a previous delivery already created, or None.""" wanted = purchase_order(payload['number']) since = ((self.today or local_today()) - timedelta(days=days)).isoformat() seen = set() for form in search_forms(payload['order']['customer']['cnpj']): found = self.request('GET', '/pedidos', params={'cpfCnpj': form, 'dataInicial': since, 'limit': 100}) for entry in found.get('itens') or []: if entry['id'] in seen: continue seen.add(entry['id']) detail = self.request('GET', f"/pedidos/{entry['id']}") if detail.get('numeroOrdemCompra') == wanted: return detail return None def tag(self, tiny_id, known=False): """The SITE DTF marcador on the order, once. A retry that finds the order already created checks first, since POST adds another.""" if known: have = self.request('GET', f'/pedidos/{tiny_id}/marcadores') have = have if isinstance(have, list) else have.get('itens') or [] if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have): return self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}]) def set_situacao(self, tiny_id, situacao): self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao}) def deliver(self, event_key, payload): event = payload.get('event') if event == 'payment_approved': return self.sale(event_key, payload) if event == 'ready' and status_updates(): return self.ready(event_key, payload) if event == 'production_started' and status_updates(): # Not past it: an order the team already invoiced stays where it is. return self.move(event_key, payload, PREPARANDO, (ABERTA, APROVADA)) if event == 'cancelled' and status_updates(): return self.move(event_key, payload, CANCELADA, (ABERTA, APROVADA, PREPARANDO, INCOMPLETA)) # Other production events have no Tiny situação and are not written. return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable', 'event': event} def sale(self, event_key, payload): """Create the order once; with status updates on, approve it once. An order is created "Aberta" and then set to "Aprovada", so a retry after a failure between the two finds it still open and finishes the job, and an order someone has already moved on is left alone.""" existing = self.find(payload) if existing: receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created', 'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))} 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, shipping=self.shipping)) 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 # Tagged before it is approved, so a failure here is retried while the order is still open. if situacao == ABERTA: self.tag(tiny_id, known=bool(existing)) receipt['marcador'] = TAG if status_updates() and situacao == ABERTA: self.set_situacao(tiny_id, APROVADA) receipt['situacao'] = SITUACOES[APROVADA] return receipt def ready(self, event_key, payload): """The order reached Finalizado: "Pronto para envio", for pickup and delivery alike (Dropstar, 2026-10-23). From there the team ships it in Tiny as any other order.""" return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA)) def move(self, event_key, payload, target, from_situacoes): """Set the order's situação to `target` when it is still in one of `from_situacoes`; anywhere else it was moved on in Tiny and stays.""" base = {'provider': 'tiny', 'event_key': event_key} tiny_id = payload.get('tiny_id') detail = self.request('GET', f'/pedidos/{tiny_id}') if tiny_id else self.find(payload, READY_SEARCH_DAYS) if not detail: raise TinyError(f"{purchase_order(payload['number'])} is not in Tiny yet; the outbox will retry") base.update(tiny_id=str(detail.get('id')), tiny_number=str(detail.get('numeroPedido'))) situacao = detail.get('situacao') if situacao not in from_situacoes: return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))} self.set_situacao(detail['id'], target) return {**base, 'status': 'status-updated', 'situacao': SITUACOES[target]}