diff --git a/src/controllers/webhook.controller.ts b/src/controllers/webhook.controller.ts index 69d95fe..674a216 100644 --- a/src/controllers/webhook.controller.ts +++ b/src/controllers/webhook.controller.ts @@ -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 | 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 => { 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[] = []; + const dispatchPromises: Promise[] = []; 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) { diff --git a/src/services/n8n.service.ts b/src/services/n8n.service.ts index 7c55bc8..8451c19 100644 --- a/src/services/n8n.service.ts +++ b/src/services/n8n.service.ts @@ -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 => { +// Resolves true once n8n accepted the payload, false if it could not be delivered. +export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise => { 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 = { @@ -51,7 +52,7 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise 0 ? configuredTtlDays : 30) * 24 * 60 * 60 * 1000; + +let sent = new Map(); +let loadedMtimeMs = 0; +// Claimed but not yet confirmed, so simultaneous duplicates produce a single send. +const inFlight = new Set(); + +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 = 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)); +} diff --git a/test/helpers.ts b/test/helpers.ts index 6407ac0..9671064 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -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) { 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', diff --git a/test/order-webhook.test.ts b/test/order-webhook.test.ts index d85298b..369eed4 100644 --- a/test/order-webhook.test.ts +++ b/test/order-webhook.test.ts @@ -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 () => { diff --git a/test/status-dedupe.test.ts b/test/status-dedupe.test.ts new file mode 100644 index 0000000..1d42eb8 --- /dev/null +++ b/test/status-dedupe.test.ts @@ -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 = {}; +const tinyOverrides: Record 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; +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); +}); diff --git a/test/stock-and-shutdown.test.ts b/test/stock-and-shutdown.test.ts index 31d76a0..bdd2ff9 100644 --- a/test/stock-and-shutdown.test.ts +++ b/test/stock-and-shutdown.test.ts @@ -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');