Files
tiny-webhook/test/order-webhook.test.ts
Cauê Faleiros e204135eb6
All checks were successful
Build and Deploy / build-and-push (push) Successful in 38s
Send each order status to the status workflow only once
Tiny fires an order webhook on every edit, not only on status changes,
and the middleware forwarded all of them, so n8n could send the customer
the same WhatsApp again (seen: order 986470642 got "enviado" twice
within 2 minutes).

Remember the last status forwarded per order and skip repeats:
- recorded only after n8n accepted it and only for orders with Tiny
  data, so failed or incomplete sends can still go through;
- claimed before sending, so simultaneous duplicates send once;
- saved to data-runtime/status_notifications_sent.json (30-day TTL) so
  redeploys don't resend; re-read when another container updates it;
- a real change back to an earlier status is still sent;
- the Graphs workflow still receives every update.
STATUS_DEDUPE_ENABLED=false turns it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:30:38 -03:00

103 lines
4.8 KiB
TypeScript

import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { setTestEnv, mockAxiosPost, tinyOrder, tinyError, axiosError, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers';
setTestEnv({});
const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller');
let tinyResponses: Record<string, Array<() => any>> = {};
const calls = mockAxiosPost(async (url, data) => {
if (!isTinyCall(url)) return { status: 200, data: {} };
const id = new URLSearchParams(data.toString()).get('id')!;
const next = tinyResponses[id]?.shift();
if (!next) throw new Error(`No mocked Tiny response left for order ${id}`);
return next();
});
const tinyCallsFor = (id: string) => calls.filter(c => isTinyCall(c.url) && new URLSearchParams(c.data.toString()).get('id') === id);
const forwardedFor = (id: string) => calls.filter(c => !isTinyCall(c.url) && String(c.data.id) === id).map(c => c.data);
let consoleCapture: ReturnType<typeof silenceConsole>;
before(() => { consoleCapture = silenceConsole(); });
after(() => consoleCapture.restore());
test('forwards the flat payload n8n relies on', async () => {
tinyResponses['1001'] = [() => tinyOrder('1001')];
await handleTinyOrderUpdate(orderWebhook(1001, 'pronto_envio', 'Pronto para envio'), fakeRes());
const [payload] = forwardedFor('1001');
assert.deepEqual(Object.keys(payload), [
'id', 'numero', 'numero_ecommerce', 'data_pedido', 'data_prevista', 'nome', 'valor', 'id_vendedor',
'nome_vendedor', 'whatsapp_vendedor', 'situacao', 'fone', 'email', 'status_processamento',
'forma_envio', 'codigo_rastreamento', 'url_rastreamento', 'itens'
]);
assert.equal(payload.situacao, 'Pronto para envio');
assert.equal(payload.forma_envio, 'X');
assert.equal(payload.fone, '(16) 99999-0000');
assert.equal(payload.numero_ecommerce, '39BAECDB7D');
assert.equal(payload.valor, 136.49);
});
test('a status change minutes later refetches instead of reusing the old status', async () => {
tinyResponses['1002'] = [
() => tinyOrder('1002', { situacao: 'Preparando envio' }),
() => tinyOrder('1002', { situacao: 'Pronto para envio' })
];
await handleTinyOrderUpdate(orderWebhook(1002, 'preparando_envio', 'Preparando envio'), fakeRes());
await handleTinyOrderUpdate(orderWebhook(1002, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.deepEqual(forwardedFor('1002').map(p => p.situacao), ['Preparando envio', 'Pronto para envio']);
assert.equal(tinyCallsFor('1002').length, 2);
});
test('a same-status duplicate webhook reuses the cached lookup and is not sent to n8n again', async () => {
tinyResponses['1003'] = [() => tinyOrder('1003')];
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1003').length, 1);
assert.equal(forwardedFor('1003').length, 1);
});
test('retries when Olist rate-limits the lookup (codigo_erro 6)', async () => {
tinyResponses['1004'] = [
() => tinyError('6', 'API bloqueada momentaneamente - muitos acessos no último minuto'),
() => tinyOrder('1004')
];
await handleTinyOrderUpdate(orderWebhook(1004, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1004').length, 2);
assert.equal(forwardedFor('1004')[0].fone, '(16) 99999-0000');
});
test('retries when the Olist request times out', async () => {
tinyResponses['1005'] = [
() => { throw axiosError('ECONNABORTED'); },
() => tinyOrder('1005')
];
await handleTinyOrderUpdate(orderWebhook(1005, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1005').length, 2);
assert.equal(forwardedFor('1005')[0].forma_envio, 'X');
});
test('does not retry a permanent Olist error, and flags the order as at risk', async () => {
tinyResponses['1006'] = [() => tinyError('32', 'Pedido não localizado')];
consoleCapture.warnings.length = 0;
await handleTinyOrderUpdate(orderWebhook(1006, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1006').length, 1);
const [payload] = forwardedFor('1006');
assert.equal(payload.fone, '');
assert.equal(payload.situacao, 'Pronto para envio');
assert.ok(consoleCapture.warnings.some(w => w.includes('[Notification at risk] Order ID 1006')));
});
test('gives up after the configured attempts when Olist stays rate-limited', async () => {
tinyResponses['1007'] = [1, 2, 3].map(() => () => tinyError('6', 'API bloqueada'));
await handleTinyOrderUpdate(orderWebhook(1007, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1007').length, 3);
assert.equal(forwardedFor('1007').length, 1);
});