feat: Site orders reach Tiny filled in as the store's own
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m6s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 58s
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m6s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 58s
Read from two of Dropstar's store orders: a paid order now carries its forma de recebimento (Pix or credit card) with one parcel on the day, the carrier with freight paid by the sender (Correios with the contract's PAC or SEDEX, Jadlog's .PACKAGE, or the DropStar carrier with "Retirar pessoalmente" and "Retirar em loja" for pickup), and the expected date in working days. Formas de envio and de frete are looked up by name and code; the two formas de recebimento and the carrier, which the app may not list, are Dropstar's ids. Category, seller and tag wait for Dropstar's answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
107
app/tiny.py
107
app/tiny.py
@@ -94,6 +94,17 @@ STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||
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.
|
||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722}
|
||||
PICKUP_CARRIER = 761565838
|
||||
# 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.
|
||||
@@ -393,9 +404,20 @@ def address(destination):
|
||||
'uf': destination['state'], 'pais': 'Brasil'}
|
||||
|
||||
|
||||
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."""
|
||||
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']:
|
||||
@@ -420,18 +442,30 @@ def order_payload(payload, contact_id, today=None, product_id=None, pickup_id=No
|
||||
'valorUnitario': money(item['unit_cents']),
|
||||
'infoAdicional': note})
|
||||
freight = order['freight']
|
||||
pickup = freight.get('service') == 'pickup'
|
||||
pedido = {'data': (today or local_today()).isoformat(),
|
||||
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': f"Site DTF · pago · {payload['order_id']}"}
|
||||
pickup_method = os.environ.get(PICKUP_SETTING, '')
|
||||
pickup_method = int(pickup_method) if pickup_method.isdigit() else pickup_id
|
||||
if pickup and pickup_method:
|
||||
pedido['transportador'] = {'formaEnvio': {'id': int(pickup_method)}}
|
||||
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:
|
||||
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
|
||||
# Paid at once, in full, as the store's orders: one parcel on the day.
|
||||
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
|
||||
if received:
|
||||
total = money(order['total_cents'])
|
||||
pedido['pagamento'] = {'formaRecebimento': {'id': received},
|
||||
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
|
||||
'formaRecebimento': {'id': received}}]}
|
||||
destination = order.get('destination')
|
||||
if destination:
|
||||
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
||||
@@ -483,6 +517,43 @@ def find_pickup(orders):
|
||||
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, '')
|
||||
@@ -531,7 +602,7 @@ class TinyOrders:
|
||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
||||
self.today = today
|
||||
self.skus = {}
|
||||
self.pickup = None
|
||||
self.carriers = {}
|
||||
# The company's names by CNPJ, for new contacts (app.cnpj.company).
|
||||
self.names = names
|
||||
|
||||
@@ -544,13 +615,11 @@ 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 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."""
|
||||
@@ -621,10 +690,8 @@ class TinyOrders:
|
||||
tiny_id, situacao = existing.get('id'), existing.get('situacao')
|
||||
else:
|
||||
contact_id = self.contact(payload['order'])
|
||||
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))
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user