- Olist lookups: 20s timeout so one hung request can't stall the serial queue; retry temporary failures (codigo_erro 6/11/35/99, timeouts, 5xx) with backoff instead of forwarding orders without phone or forma_envio. Log "[Notification at risk]" when that still happens. - n8n forwarding: timeout plus retries, only when n8n certainly didn't run the workflow (connection refused, 502/503, 404 while restarting), so retries can't send a customer the same WhatsApp twice. Stop logging the start of N8N_AUTH_TOKEN. - On SIGTERM, stop accepting requests and finish webhooks already acked to Tiny (up to SHUTDOWN_GRACE_MS, default 50s). - Keep stock_memory.json and stock_log.csv on the data-runtime volume so stock stats survive redeploys. - Add a node:test suite (npm test) covering the payload n8n reads, the status cache, burst queueing, retries, stock files and shutdown drain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
103 lines
4.8 KiB
TypeScript
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', 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, 2);
|
|
});
|
|
|
|
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);
|
|
});
|