Send each order status to the status workflow only once
All checks were successful
Build and Deploy / build-and-push (push) Successful in 38s

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>
This commit is contained in:
Cauê Faleiros
2026-10-08 15:30:38 -03:00
parent c5e168429d
commit e204135eb6
7 changed files with 230 additions and 12 deletions

View File

@@ -1,4 +1,7 @@
import axios from 'axios';
import fs from 'fs';
import os from 'os';
import path from 'path';
// Each test file runs in its own process; set env before requiring app modules,
// since they read their config at load time.
@@ -9,6 +12,7 @@ export function setTestEnv(overrides: Record<string, string>) {
delete process.env.NEXSTAR_GRAPHS_API_URL;
delete process.env.TINY_LIVE_MAX_QUEUE_WAIT_MS;
Object.assign(process.env, {
RUNTIME_DATA_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'tiny-webhook-test-')),
TINY_API_TOKEN: 'mock-token',
N8N_WEBHOOK_STATUS: 'http://n8n.test/status',
TINY_LIVE_REQUEST_DELAY_MS: '0',

View File

@@ -50,13 +50,13 @@ test('a status change minutes later refetches instead of reusing the old status'
assert.equal(tinyCallsFor('1002').length, 2);
});
test('a same-status duplicate webhook reuses the cached lookup', async () => {
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, 2);
assert.equal(forwardedFor('1003').length, 1);
});
test('retries when Olist rate-limits the lookup (codigo_erro 6)', async () => {

View File

@@ -0,0 +1,98 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import path from 'path';
import { setTestEnv, mockAxiosPost, tinyOrder, tinyError, axiosError, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers';
// No lookup cache, so every webhook is a fresh Olist lookup like duplicates minutes apart.
setTestEnv({ N8N_WEBHOOK_GRAPHS: 'http://n8n.test/graphs', TINY_ORDER_DETAILS_CACHE_TTL_MS: '0' });
const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller');
const currentStatus: Record<string, string> = {};
const tinyOverrides: Record<string, Array<() => any>> = {};
const n8nStatusOverrides: Array<() => any> = [];
const calls = mockAxiosPost(async (url, data) => {
if (isTinyCall(url)) {
const id = new URLSearchParams(data.toString()).get('id')!;
const override = tinyOverrides[id]?.shift();
return override ? override() : tinyOrder(id, { situacao: currentStatus[id] });
}
const override = url === 'http://n8n.test/status' ? n8nStatusOverrides.shift() : undefined;
return override ? override() : { status: 200, data: {} };
});
const sentTo = (url: string, id: string) => calls.filter(c => c.url === url && String(c.data.id) === id).map(c => c.data.situacao);
const statusSends = (id: string) => sentTo('http://n8n.test/status', id);
const graphsSends = (id: string) => sentTo('http://n8n.test/graphs', id);
const webhook = (id: string, situacao: string) => {
currentStatus[id] = situacao;
return handleTinyOrderUpdate(orderWebhook(id, situacao.toLowerCase().replace(/ /g, '_'), situacao), fakeRes());
};
let capture: ReturnType<typeof silenceConsole>;
before(() => { capture = silenceConsole(); });
after(() => {
capture.restore();
fs.rmSync(process.env.RUNTIME_DATA_DIR!, { recursive: true, force: true });
});
test('a repeated status is sent to the status workflow once, but Graphs still gets every update', async () => {
await webhook('4001', 'Enviado');
await webhook('4001', 'Enviado');
await webhook('4001', 'Enviado');
assert.deepEqual(statusSends('4001'), ['Enviado']);
assert.equal(graphsSends('4001').length, 3);
});
test('simultaneous duplicates produce a single send', async () => {
currentStatus['4002'] = 'Pronto para envio';
await Promise.all([1, 2, 3].map(() => webhook('4002', 'Pronto para envio')));
assert.deepEqual(statusSends('4002'), ['Pronto para envio']);
});
test('every real status change is sent, including going back to an earlier status', async () => {
for (const situacao of ['Aprovado', 'Preparando envio', 'Pronto para envio', 'Preparando envio', 'Pronto para envio', 'Enviado']) {
await webhook('4003', situacao);
}
assert.deepEqual(statusSends('4003'), ['Aprovado', 'Preparando envio', 'Pronto para envio', 'Preparando envio', 'Pronto para envio', 'Enviado']);
});
test('a send n8n rejected is not recorded, so the next webhook for that status still goes', async () => {
n8nStatusOverrides.push(() => { throw axiosError('ERR_BAD_REQUEST', 400); });
await webhook('4004', 'Pronto para envio');
await webhook('4004', 'Pronto para envio');
await webhook('4004', 'Pronto para envio');
assert.deepEqual(statusSends('4004'), ['Pronto para envio', 'Pronto para envio']);
});
test('an order forwarded without Olist data does not block the next complete one', async () => {
tinyOverrides['4005'] = [() => tinyError('32', 'Pedido não localizado')];
await webhook('4005', 'Pronto para envio');
await webhook('4005', 'Pronto para envio');
await webhook('4005', 'Pronto para envio');
const sends = calls.filter(c => c.url === 'http://n8n.test/status' && String(c.data.id) === '4005').map(c => c.data);
assert.equal(sends.length, 2);
assert.equal(sends[0].fone, '');
assert.equal(sends[1].fone, '(16) 99999-0000');
});
test('sent statuses are saved on the runtime volume and survive a restart', async () => {
await webhook('4006', 'Entregue');
const saved = JSON.parse(fs.readFileSync(path.join(process.env.RUNTIME_DATA_DIR!, 'status_notifications_sent.json'), 'utf-8'));
assert.equal(saved['4006'].situacao, 'Entregue');
// Load a fresh copy of the module, as a new container would.
const modulePath = require.resolve('../src/services/status-dedupe.service');
delete require.cache[modulePath];
const fresh = require('../src/services/status-dedupe.service');
assert.equal(fresh.claimStatusNotification('4006', 'Entregue'), false);
assert.equal(fresh.claimStatusNotification('4006', 'Enviado'), true);
});

View File

@@ -1,14 +1,13 @@
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import express from 'express';
import { AddressInfo } from 'net';
import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, isTinyCall, silenceConsole } from './helpers';
const runtimeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tiny-webhook-test-'));
setTestEnv({ RUNTIME_DATA_DIR: runtimeDir, N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' });
setTestEnv({ N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' });
const runtimeDir = process.env.RUNTIME_DATA_DIR!;
const { handleTinyStockUpdate } = require('../src/controllers/webhook.controller');
const webhookRoutes = require('../src/routes/webhook.route');