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