feat: Tiny follows printing and cancellation
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled

With TINY_STATUS_UPDATES on, an order entering Imprimindo becomes
"Preparando envio" in Tiny, and a cancelled order "Cancelada", next to the
"Aprovada" on payment and the pickup "Pronto para envio" there already.
Neither sends a WhatsApp in the client's n8n. An order the team already
moved further in Tiny is never moved back, and an invoiced one is not
cancelled here: its nota fiscal is cancelled in Tiny. Cancelling a paid
order now tells Tiny, which it did not before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-16 18:45:23 -03:00
parent 1f2358c8b5
commit dbf1efc112
5 changed files with 77 additions and 13 deletions

View File

@@ -269,7 +269,7 @@ def payment_events(state: Literal['open','resolved','all'] = 'open',
@router.get('/api/operator/events')
def events(provider: Literal['tiny'] | None = None,
status: Literal['delivered','queued','failing'] | None = None,
event: Literal['payment_approved','production_started','correction_needed','ready'] | None = None,
event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None,
order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))):
"""The integration send log, newest first, filtered, by page with a total."""
@@ -496,13 +496,20 @@ def release_files(c, uploads):
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
is refunded here (that is done at the provider) and Tiny is not told."""
is refunded here (that is done at the provider); Tiny is told, so the
order is cancelled there too while it was not invoiced (app/tiny.py)."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING number''',
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING *''',
(user, body.note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
if not payments.is_test(row):
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
{'order_id': str(uid), 'number': row['number'], 'event': 'cancelled', 'reason': body.note,
'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')})
audit('order_cancelled', order=row['number'], operator=user)
return {'ok': True}

View File

@@ -22,12 +22,20 @@ carries numeroOrdemCompra = "DTF-<order number>", 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.
Customer notices: the client already sends WhatsApp messages from Tiny's
order situação (Tiny webhook -> their middleware -> n8n). With
TINY_STATUS_UPDATES on, a paid order is set to "Aprovada" and a finished
pickup order to "Pronto para envio", so those notices reach Site customers
from the same number and templates; the system's own WhatsApp sender stays
off. Pickup orders carry the client's "retirar pessoalmente" forma de envio.
Customer notices: the client sends WhatsApp messages from Tiny's order
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
envio (pickup only), Enviado and Entregue. With TINY_STATUS_UPDATES on, the
Kanban moves the Tiny order along with it:
paid (Arte recebida) -> Aprovada (the "approved" notice)
Imprimindo -> Preparando envio (no notice)
Finalizado, pickup -> Pronto para envio (the pickup notice)
Finalizado, delivery -> unchanged: the team invoices and ships in Tiny
cancelled -> Cancelada (no notice)
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
@@ -72,6 +80,7 @@ SEARCH_DAYS = 7
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)
@@ -591,6 +600,11 @@ class TinyOrders:
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}
@@ -627,13 +641,19 @@ class TinyOrders:
order = payload.get('order') or {}
if (order.get('freight') or {}).get('service') != 'pickup':
return {**base, 'status': 'not-applicable', 'event': 'ready'}
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 in (PRONTO_ENVIO, ENVIADA, ENTREGUE, CANCELADA, NAO_ENTREGUE):
if situacao not in from_situacoes:
return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))}
self.set_situacao(detail['id'], PRONTO_ENVIO)
return {**base, 'status': 'status-updated', 'situacao': SITUACOES[PRONTO_ENVIO]}
self.set_situacao(detail['id'], target)
return {**base, 'status': 'status-updated', 'situacao': SITUACOES[target]}