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,6 +1,7 @@
import { Request, Response } from 'express';
import { sendToN8n } from '../services/n8n.service';
import { sendTinyOrderToGraphs } from '../services/graphs.service';
import { claimStatusNotification, confirmStatusNotification, releaseStatusNotification } from '../services/status-dedupe.service';
import axios from 'axios';
import fs from 'fs';
import path from 'path';
@@ -240,6 +241,32 @@ async function getOrFetchOrderDetails(orderId: string, webhookStatus: string, ti
return fetchPromise;
}
// Only real status changes reach the status workflow, so repeated webhooks for the same
// status (Tiny sends one on every order edit) don't send the customer the same WhatsApp.
// Orders without Tiny data are forwarded but not recorded, so a later complete one still goes.
function dispatchToStatusWorkflow(orderId: string, payload: { situacao: string }, enriched: boolean, statusUrl: string): Promise<boolean> | null {
const situacao = String(payload.situacao || '').trim();
if (!enriched || !situacao) {
console.log('-> Preparing dispatch to Status Workflow...');
return sendToN8n(payload, statusUrl);
}
if (!claimStatusNotification(orderId, situacao)) {
console.log(`-> Skipping Status Workflow for Order ID: ${orderId}: "${situacao}" was already sent.`);
return null;
}
console.log('-> Preparing dispatch to Status Workflow...');
return sendToN8n(payload, statusUrl).then(delivered => {
if (delivered) {
confirmStatusNotification(orderId, situacao);
} else {
releaseStatusNotification(orderId, situacao);
}
return delivered;
});
}
export const handleTinyOrderUpdate = async (req: Request, res: Response): Promise<void> => {
try {
// 1. Security Check: Verify token from Tiny
@@ -331,11 +358,11 @@ export const handleTinyOrderUpdate = async (req: Request, res: Response): Promis
console.log(`[Config Check] Status URL: ${statusUrl ? 'CONFIGURED' : 'MISSING'}`);
console.log(`[Config Check] Graphs URL: ${graphsUrl ? 'CONFIGURED' : 'MISSING'} (${graphsUrl})`);
const dispatchPromises: Promise<void>[] = [];
const dispatchPromises: Promise<unknown>[] = [];
if (statusUrl) {
console.log('-> Preparing dispatch to Status Workflow...');
dispatchPromises.push(sendToN8n(finalPayload, statusUrl));
const statusPromise = dispatchToStatusWorkflow(String(orderId), finalPayload, Boolean(fullOrderDetails), statusUrl);
if (statusPromise) dispatchPromises.push(statusPromise);
}
if (graphsUrl) {

View File

@@ -26,13 +26,14 @@ function isSafeToRetry(error: any): boolean {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<void> => {
// Resolves true once n8n accepted the payload, false if it could not be delivered.
export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<boolean> => {
const n8nWebhookUrl = targetWebhookUrl || process.env.N8N_WEBHOOK_URL;
const n8nAuthToken = process.env.N8N_AUTH_TOKEN;
if (!n8nWebhookUrl) {
console.error('N8N_WEBHOOK_URL is not defined in environment variables.');
return;
return false;
}
const headers: Record<string, string> = {
@@ -51,7 +52,7 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<v
console.log(`Forwarding payload to n8n at ${n8nWebhookUrl}...`);
const response = await axios.post(n8nWebhookUrl, data, { headers, timeout: N8N_REQUEST_TIMEOUT_MS });
console.log(`Successfully forwarded to n8n. Status: ${response.status}`);
return;
return true;
} catch (error: any) {
const reason = error.response ? `HTTP ${error.response.status}` : (error.code || error.message);
@@ -66,7 +67,8 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<v
if (error.response) {
console.error('n8n Response:', error.response.status, error.response.data);
}
return;
return false;
}
}
return false;
};

View File

@@ -0,0 +1,88 @@
import fs from 'fs';
import path from 'path';
// Tiny fires an order webhook on every edit, not only on status changes, so the same
// status can arrive several times and n8n would send the customer the same WhatsApp
// again. Remember the last status forwarded to the status workflow per order and skip
// repeats. Saved on the data-runtime volume so redeploys don't resend.
type SentStatus = { situacao: string; at: number };
const RUNTIME_DATA_DIR = process.env.RUNTIME_DATA_DIR || path.join(process.cwd(), 'data-runtime');
const STATE_FILE = path.join(RUNTIME_DATA_DIR, 'status_notifications_sent.json');
const ENABLED = process.env.STATUS_DEDUPE_ENABLED !== 'false';
const configuredTtlDays = Number(process.env.STATUS_DEDUPE_TTL_DAYS || 30);
const TTL_MS = (Number.isFinite(configuredTtlDays) && configuredTtlDays > 0 ? configuredTtlDays : 30) * 24 * 60 * 60 * 1000;
let sent = new Map<string, SentStatus>();
let loadedMtimeMs = 0;
// Claimed but not yet confirmed, so simultaneous duplicates produce a single send.
const inFlight = new Set<string>();
const claimKey = (orderId: string, situacao: string) => `${orderId}:${situacao}`;
// Re-read when the file changed on disk (e.g. the old container during a start-first
// redeploy), keeping the newest entry per order.
function syncFromDisk() {
let mtimeMs: number;
try {
mtimeMs = fs.statSync(STATE_FILE).mtimeMs;
} catch {
return;
}
if (mtimeMs <= loadedMtimeMs) return;
try {
const onDisk: Record<string, SentStatus> = JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'));
for (const [orderId, entry] of Object.entries(onDisk)) {
const current = sent.get(orderId);
if (!current || entry.at > current.at) sent.set(orderId, entry);
}
loadedMtimeMs = mtimeMs;
} catch (error: any) {
console.error(`[Status Dedupe] Could not read ${STATE_FILE}: ${error.message}`);
}
}
function persist() {
syncFromDisk();
const cutoff = Date.now() - TTL_MS;
for (const [orderId, entry] of sent) {
if (entry.at < cutoff) sent.delete(orderId);
}
try {
fs.mkdirSync(RUNTIME_DATA_DIR, { recursive: true });
const tmpFile = `${STATE_FILE}.${process.pid}.tmp`;
fs.writeFileSync(tmpFile, JSON.stringify(Object.fromEntries(sent)));
fs.renameSync(tmpFile, STATE_FILE);
loadedMtimeMs = fs.statSync(STATE_FILE).mtimeMs;
} catch (error: any) {
console.error(`[Status Dedupe] Could not save ${STATE_FILE}: ${error.message}`);
}
}
// True when this order+status should go to the status workflow; the caller must then
// confirm (sent) or release (failed) the claim.
export function claimStatusNotification(orderId: string, situacao: string): boolean {
if (!ENABLED) return true;
syncFromDisk();
const key = claimKey(orderId, situacao);
if (sent.get(orderId)?.situacao === situacao || inFlight.has(key)) return false;
inFlight.add(key);
return true;
}
export function confirmStatusNotification(orderId: string, situacao: string) {
if (!ENABLED) return;
inFlight.delete(claimKey(orderId, situacao));
sent.set(orderId, { situacao, at: Date.now() });
persist();
}
export function releaseStatusNotification(orderId: string, situacao: string) {
inFlight.delete(claimKey(orderId, situacao));
}

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');