From dbf1efc1127772c090667a26e473ab287a7b82f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 16 Oct 2026 18:45:23 -0300 Subject: [PATCH] feat: Tiny follows printing and cancellation 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 --- app/api/operator.py | 13 ++++++++++--- app/tiny.py | 38 ++++++++++++++++++++++++++++--------- tests/order_actions_test.py | 6 ++++++ tests/test_tiny.py | 31 ++++++++++++++++++++++++++++++ web/kanban.js | 2 +- 5 files changed, 77 insertions(+), 13 deletions(-) diff --git a/app/api/operator.py b/app/api/operator.py index 80dc459..58cf347 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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} diff --git a/app/tiny.py b/app/tiny.py index fd12b3e..8d21620 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -22,12 +22,20 @@ 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. -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]} diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 0252d17..19f65f6 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -72,6 +72,12 @@ def run(): board = client.call('/operator/board', operator=True) order = next(o for o in board['orders'] if o['id'] == str(paid_order)) assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu' + # Tiny is told, once (app/tiny.py cancels it there while not invoiced). + with db.connect() as c: + told = c.execute("SELECT provider,payload FROM dtf_local.outbox WHERE event_key=%s", + (f'{paid_order}:cancelled:tiny',)).fetchall() + assert [(t['provider'], t['payload']['event'], t['payload']['reason']) for t in told] == \ + [('tiny', 'cancelled', 'Cliente desistiu')], told # The automatic folder hears it is cancelled, and so removes its files. held = client.call('/operator/queue/folder', {'early': True, 'held': [str(paid_order)]}, operator=True) assert held['states'] == {str(paid_order): 'cancelled'}, held['states'] diff --git a/tests/test_tiny.py b/tests/test_tiny.py index a42a0b3..532ce5d 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -264,6 +264,37 @@ class TinyStatusTests(FakeTinyCase): self.assertEqual(ready['status'], 'not-applicable') self.assertEqual(self.calls, []) + @mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'}) + def test_printing_is_preparando_envio_but_never_moves_an_invoiced_order_back(self): + sale = self.tiny.deliver('k1', PAID) + started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']} + moved = self.tiny.deliver('k2', started) + self.assertEqual((moved['status'], moved['situacao'], self.orders[0]['situacao']), + ('status-updated', 'Preparando envio', 4)) + self.orders[0]['situacao'] = 1 # the team invoiced it + self.assertEqual(self.tiny.deliver('k2', started)['status'], 'status-unchanged') + self.assertEqual(self.orders[0]['situacao'], 1) + + @mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'}) + def test_a_cancelled_order_is_cancelled_in_tiny_unless_invoiced(self): + self.tiny.deliver('k1', PAID) + cancelled = {**READY, 'event': 'cancelled', 'order': PAID['order']} + done = self.tiny.deliver('k3', cancelled) + self.assertEqual((done['status'], done['situacao'], self.orders[0]['situacao']), + ('status-updated', 'Cancelada', 2)) + self.orders[0]['situacao'] = 1 + kept = self.tiny.deliver('k3', cancelled) + self.assertEqual((kept['status'], kept['situacao'], self.orders[0]['situacao']), + ('status-unchanged', 'Faturada', 1)) + + def test_printing_and_cancelling_change_nothing_while_status_updates_are_off(self): + self.tiny.deliver('k1', PAID) + self.calls.clear() + for event in ('production_started', 'cancelled'): + self.assertEqual(self.tiny.deliver('k', {**READY, 'event': event, 'order': PAID['order']})['status'], + 'not-applicable') + self.assertEqual(self.calls, []) + def test_pickup_orders_carry_the_pickup_forma_de_envio(self): self.assertEqual(order_payload(PICKUP, 1)['transportador'], {'formaEnvio': {'id': 77}}) self.assertNotIn('transportador', order_payload(PAID, 1)) diff --git a/web/kanban.js b/web/kanban.js index 3934599..a0f5a73 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -9,7 +9,7 @@ const STAGE_COLORS={rec:'var(--rec)',tra:'var(--tra)',fil:'var(--fil)',imp:'var( const FLOW=['rec','tra','fil','imp','fin']; const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'}; const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'}; -const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto'}; +const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'}; const LATE_HOURS=4; // Payment outcomes are recorded by the API in English; operators read Portuguese. function outcomeText(outcome){