diff --git a/package.json b/package.json index 4d7b67b..edc5263 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "sync:product-structures": "tsx src/scripts/sync-product-structures.ts", "sync:product-structures:v3": "tsx src/scripts/sync-product-structures-v3.ts", "sync:production-orders": "tsx src/scripts/sync-production-orders.ts", - "test": "echo \"Error: no test specified\" && exit 1" + "test": "node --import tsx --test test/*.test.ts" }, "keywords": [], "author": "", diff --git a/src/controllers/webhook.controller.ts b/src/controllers/webhook.controller.ts index 287a8fd..69d95fe 100644 --- a/src/controllers/webhook.controller.ts +++ b/src/controllers/webhook.controller.ts @@ -5,6 +5,11 @@ import axios from 'axios'; import fs from 'fs'; import path from 'path'; +// Stock stats live on the mounted volume so they survive redeploys. +const RUNTIME_DATA_DIR = process.env.RUNTIME_DATA_DIR || path.join(process.cwd(), 'data-runtime'); +const STOCK_MEMORY_FILE = path.join(RUNTIME_DATA_DIR, 'stock_memory.json'); +export const STOCK_LOG_FILE = path.join(RUNTIME_DATA_DIR, 'stock_log.csv'); + type CachedOrderDetails = { expiresAt: number; fullOrderDetails: any; @@ -30,6 +35,12 @@ const LIVE_TINY_REQUEST_DELAY_MS = numberEnv('TINY_LIVE_REQUEST_DELAY_MS', 6000) // forwards an order with no phone or forma_envio, which n8n can't notify. Keep this a // last-resort valve (~150 queued webhooks at 6s), not something a burst can hit. const LIVE_TINY_MAX_QUEUE_WAIT_MS = numberEnv('TINY_LIVE_MAX_QUEUE_WAIT_MS', 900000); +// Without a timeout one hung Olist request would stall the whole serial queue. +const TINY_REQUEST_TIMEOUT_MS = numberEnv('TINY_REQUEST_TIMEOUT_MS', 20000); +const TINY_LOOKUP_MAX_ATTEMPTS = Math.max(1, numberEnv('TINY_LOOKUP_MAX_ATTEMPTS', 3)); +const TINY_LOOKUP_RETRY_DELAY_MS = numberEnv('TINY_LOOKUP_RETRY_DELAY_MS', 30000); +// Olist API v2 codigo_erro values worth retrying: 6/11 rate limited, 35 unexpected error, 99 maintenance. +const RETRYABLE_TINY_ERROR_CODES = new Set(['6', '11', '35', '99']); let liveTinyQueueTail: Promise = Promise.resolve(); let liveTinyNextRequestAt = 0; let liveTinyPendingRequests = 0; @@ -105,10 +116,44 @@ async function runWithLiveTinySlot(orderId: string, servicePhp: string, opera async function tinyLivePost(orderId: string, servicePhp: string, params: URLSearchParams) { return runWithLiveTinySlot(orderId, servicePhp, () => axios.post(`https://api.tiny.com.br/api2/${servicePhp}`, params, { - headers: { 'Content-Type': 'application/x-www-form-urlencoded' } + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + timeout: TINY_REQUEST_TIMEOUT_MS })); } +function isRetryableTinyFailure(error: any): boolean { + if (error instanceof LiveTinyQueueBacklogError) return false; + const status = error?.response?.status; + // No response (timeout, connection reset, DNS) or a server-side error. + return !error?.response || status === 429 || status >= 500; +} + +// Fetches pedido.obter, retrying only temporary failures so a short Olist hiccup +// doesn't forward the order without phone/forma_envio. +async function fetchOrderFromTinyWithRetry(orderId: string, params: URLSearchParams) { + for (let attempt = 1; ; attempt++) { + let retryReason = ''; + try { + const apiResponse = await tinyLivePost(orderId, 'pedido.obter.php', params); + const retorno = apiResponse.data?.retorno; + if (retorno?.status === 'OK') return apiResponse; + + const errorCode = String(retorno?.codigo_erro ?? ''); + if (!RETRYABLE_TINY_ERROR_CODES.has(errorCode) || attempt >= TINY_LOOKUP_MAX_ATTEMPTS) { + return apiResponse; + } + retryReason = `codigo_erro ${errorCode} ${JSON.stringify(retorno?.erros || '')}`; + } catch (error: any) { + if (!isRetryableTinyFailure(error) || attempt >= TINY_LOOKUP_MAX_ATTEMPTS) throw error; + retryReason = error.code || error.message; + } + + const delayMs = TINY_LOOKUP_RETRY_DELAY_MS * attempt; + console.warn(`Tiny lookup for Order ID ${orderId} failed (${retryReason}). Retry ${attempt}/${TINY_LOOKUP_MAX_ATTEMPTS - 1} in ${delayMs}ms.`); + await sleep(delayMs); + } +} + async function fetchOrderDetailsFromTiny(orderId: string, tinyApiToken: string): Promise { console.log(`Fetching full details for Order ID: ${orderId} from Tiny API...`); const params = new URLSearchParams(); @@ -116,7 +161,7 @@ async function fetchOrderDetailsFromTiny(orderId: string, tinyApiToken: string): params.append('id', orderId); params.append('formato', 'JSON'); - const apiResponse = await tinyLivePost(orderId, 'pedido.obter.php', params); + const apiResponse = await fetchOrderFromTinyWithRetry(orderId, params); if (apiResponse.data?.retorno?.status !== 'OK') { console.error('Tiny API returned an error:', apiResponse.data?.retorno?.erros || 'Unknown error'); @@ -252,6 +297,10 @@ export const handleTinyOrderUpdate = async (req: Request, res: Response): Promis console.warn('TINY_API_TOKEN is not set in environment variables. Skipping full details fetch.'); } + if (!fullOrderDetails) { + console.warn(`[Notification at risk] Order ID ${orderId} (${payload.dados?.descricaoSituacao || 'unknown status'}) is forwarded without Tiny data: no phone or forma_envio for n8n.`); + } + // Build the exact flat JSON payload requested by the user const finalPayload = { id: fullOrderDetails?.id || payload.dados?.id || "", @@ -333,7 +382,8 @@ export const handleTinyStockUpdate = async (req: Request, res: Response): Promis } // --- SMART MEMORY & STATS LOGIC --- - const memoryFile = path.join(process.cwd(), 'stock_memory.json'); + fs.mkdirSync(RUNTIME_DATA_DIR, { recursive: true }); + const memoryFile = STOCK_MEMORY_FILE; let memory: Record = {}; // Load memory if it exists @@ -404,7 +454,7 @@ export const handleTinyStockUpdate = async (req: Request, res: Response): Promis // --- CSV LOGGING FOR ANALYSIS --- if (deltaEstoque !== 0 || estoqueAntigo === undefined) { - const csvFile = path.join(process.cwd(), 'stock_log.csv'); + const csvFile = STOCK_LOG_FILE; const timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); const oldStockStr = estoqueAntigo !== undefined ? estoqueAntigo : 'NEW'; diff --git a/src/index.ts b/src/index.ts index 3974c36..63866c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import express, { Express, Request, Response } from 'express'; import dotenv from 'dotenv'; -import webhookRoutes from './routes/webhook.route'; +import webhookRoutes, { drainWebhookWork } from './routes/webhook.route'; +import { STOCK_LOG_FILE } from './controllers/webhook.controller'; import { spawn } from 'child_process'; import path from 'path'; import fs from 'fs'; @@ -585,8 +586,7 @@ app.get('/api/stock-logs/download', (req: Request, res: Response) => { return; } - const csvFile = path.join(process.cwd(), 'stock_log.csv'); - const fs = require('fs'); + const csvFile = STOCK_LOG_FILE; if (fs.existsSync(csvFile)) { res.download(csvFile, 'estoque_log.csv'); } else { @@ -594,6 +594,28 @@ app.get('/api/stock-logs/download', (req: Request, res: Response) => { } }); -app.listen(port, () => { +const server = app.listen(port, () => { console.log(`[server]: Middleware server is running at http://localhost:${port}`); }); + +// On redeploy, stop accepting requests but finish queued webhook work (already acked to +// Tiny) so those notifications aren't lost. Keep below the stack's stop_grace_period. +const SHUTDOWN_GRACE_MS = Number(process.env.SHUTDOWN_GRACE_MS || 50000); +let shuttingDown = false; + +async function shutdown(signal: string) { + if (shuttingDown) return; + shuttingDown = true; + console.log(`[server]: ${signal} received. Finishing in-flight webhooks (up to ${SHUTDOWN_GRACE_MS}ms)...`); + server.close(); + const remaining = await drainWebhookWork(SHUTDOWN_GRACE_MS); + if (remaining > 0) { + console.warn(`[server]: Shutting down with ${remaining} webhook(s) still in progress; they will be lost.`); + } else { + console.log('[server]: All in-flight webhooks finished. Exiting.'); + } + process.exit(0); +} + +process.on('SIGTERM', () => { void shutdown('SIGTERM'); }); +process.on('SIGINT', () => { void shutdown('SIGINT'); }); diff --git a/src/routes/webhook.route.ts b/src/routes/webhook.route.ts index f3e5f80..b9b2a0f 100644 --- a/src/routes/webhook.route.ts +++ b/src/routes/webhook.route.ts @@ -1,10 +1,32 @@ -import { Router } from 'express'; +import { Router, Request, Response } from 'express'; import { handleTinyOrderUpdate, handleTinyStockUpdate, handleTinyGraphsUpdate } from '../controllers/webhook.controller'; const router = Router(); -router.post('/tiny/order-status', handleTinyOrderUpdate); -router.post('/tiny/stock-update', handleTinyStockUpdate); -router.post('/tiny/graphs-update', handleTinyGraphsUpdate); +// Handlers ack Tiny first and keep working afterwards (queue, lookup, n8n forward). +// Track that work so a shutdown can finish it instead of dropping notifications. +const pendingWork = new Set>(); -export default router; \ No newline at end of file +const tracked = (handler: (req: Request, res: Response) => Promise) => (req: Request, res: Response) => { + const work: Promise = handler(req, res).finally(() => pendingWork.delete(work)); + pendingWork.add(work); + return work; +}; + +// Resolves once all in-flight webhook work is done or the timeout passes; returns how many are left. +export async function drainWebhookWork(timeoutMs: number): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise(resolve => { timer = setTimeout(resolve, timeoutMs); }); + while (pendingWork.size > 0) { + const done = await Promise.race([Promise.allSettled([...pendingWork]).then(() => true), timeout.then(() => false)]); + if (!done) break; + } + clearTimeout(timer); + return pendingWork.size; +} + +router.post('/tiny/order-status', tracked(handleTinyOrderUpdate)); +router.post('/tiny/stock-update', tracked(handleTinyStockUpdate)); +router.post('/tiny/graphs-update', tracked(handleTinyGraphsUpdate)); + +export default router; diff --git a/src/services/n8n.service.ts b/src/services/n8n.service.ts index 059d4d4..7c55bc8 100644 --- a/src/services/n8n.service.ts +++ b/src/services/n8n.service.ts @@ -1,5 +1,31 @@ import axios from 'axios'; +const numberEnv = (name: string, fallback: number) => { + const raw = process.env[name]; + if (raw === undefined || raw.trim() === '') return fallback; + + const value = Number(raw); + return Number.isFinite(value) && value >= 0 ? value : fallback; +}; + +const N8N_REQUEST_TIMEOUT_MS = numberEnv('N8N_REQUEST_TIMEOUT_MS', 30000); +const N8N_MAX_ATTEMPTS = Math.max(1, numberEnv('N8N_MAX_ATTEMPTS', 5)); +const N8N_RETRY_DELAY_MS = numberEnv('N8N_RETRY_DELAY_MS', 5000); + +// Retry only when n8n certainly did not run the workflow, so a retry can't send a +// customer the same WhatsApp twice: the connection never opened, the proxy says n8n is +// down (502/503), or n8n hasn't registered the webhook yet while restarting (404). +// Timeouts, resets and 504 are ambiguous (n8n may have received it), so they aren't retried. +const RETRYABLE_CONNECTION_CODES = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT']); +const RETRYABLE_STATUSES = new Set([404, 502, 503]); + +function isSafeToRetry(error: any): boolean { + if (error.response) return RETRYABLE_STATUSES.has(error.response.status); + return RETRYABLE_CONNECTION_CODES.has(error.code); +} + +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise => { const n8nWebhookUrl = targetWebhookUrl || process.env.N8N_WEBHOOK_URL; const n8nAuthToken = process.env.N8N_AUTH_TOKEN; @@ -9,27 +35,38 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise = { - 'Content-Type': 'application/json' - }; + const headers: Record = { + 'Content-Type': 'application/json' + }; - if (n8nAuthToken) { - // Send exactly what the user typed in the environment variable - headers['Authorization'] = n8nAuthToken; - console.log(`DEBUG: Sending Authorization header starting with: ${n8nAuthToken.substring(0, 8)}...`); - } else { - console.log(`DEBUG: No N8N_AUTH_TOKEN found in environment variables. Sending request WITHOUT Authorization header!`); - } + if (n8nAuthToken) { + // Send exactly what the user typed in the environment variable + headers['Authorization'] = n8nAuthToken; + } else { + console.log(`DEBUG: No N8N_AUTH_TOKEN found in environment variables. Sending request WITHOUT Authorization header!`); + } - const response = await axios.post(n8nWebhookUrl, data, { headers }); - console.log(`Successfully forwarded to n8n. Status: ${response.status}`); - } catch (error: any) { - console.error('Failed to forward payload to n8n.', error.message); - if (error.response) { - console.error('n8n Response:', error.response.status, error.response.data); + for (let attempt = 1; attempt <= N8N_MAX_ATTEMPTS; attempt++) { + try { + 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; + } catch (error: any) { + const reason = error.response ? `HTTP ${error.response.status}` : (error.code || error.message); + + if (isSafeToRetry(error) && attempt < N8N_MAX_ATTEMPTS) { + const delayMs = N8N_RETRY_DELAY_MS * attempt; + console.warn(`Failed to forward payload to n8n (${reason}). Retry ${attempt}/${N8N_MAX_ATTEMPTS - 1} in ${delayMs}ms.`); + await sleep(delayMs); + continue; + } + + console.error(`Failed to forward payload to n8n after ${attempt} attempt(s) (${reason}).`, error.message); + if (error.response) { + console.error('n8n Response:', error.response.status, error.response.data); + } + return; } } }; diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..6407ac0 --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,89 @@ +import axios from 'axios'; + +// Each test file runs in its own process; set env before requiring app modules, +// since they read their config at load time. +export function setTestEnv(overrides: Record) { + delete process.env.TINY_WEBHOOK_SECRET; + delete process.env.N8N_WEBHOOK_GRAPHS; + delete process.env.GRAPHS_API_URL; + delete process.env.NEXSTAR_GRAPHS_API_URL; + delete process.env.TINY_LIVE_MAX_QUEUE_WAIT_MS; + Object.assign(process.env, { + TINY_API_TOKEN: 'mock-token', + N8N_WEBHOOK_STATUS: 'http://n8n.test/status', + TINY_LIVE_REQUEST_DELAY_MS: '0', + TINY_LOOKUP_RETRY_DELAY_MS: '5', + N8N_RETRY_DELAY_MS: '5', + ...overrides + }); +} + +export type PostCall = { url: string; data: any }; +type PostHandler = (url: string, data: any) => Promise; + +// Replaces axios.post for the whole process. Returns the recorded calls. +export function mockAxiosPost(handler: PostHandler): PostCall[] { + const calls: PostCall[] = []; + (axios as any).post = async (url: string, data: any) => { + calls.push({ url, data }); + return handler(url, data); + }; + return calls; +} + +export function tinyOrder(id: string, overrides: Record = {}) { + return { + data: { + retorno: { + status: 'OK', + status_processamento: '3', + pedido: { + id, + numero: '140255', + numero_ecommerce: '39BAECDB7D', + data_pedido: '08/10/2026', + data_prevista: '08/10/2026', + cliente: { nome: 'Cliente Teste', celular: '(16) 99999-0000', email: 'cliente@test' }, + total_pedido: '136.49', + id_vendedor: '977231477', + nome_vendedor: 'Lais Sousa Da Silva', + situacao: 'Pronto para envio', + forma_envio: 'X', + codigo_rastreamento: '', + url_rastreamento: '', + itens: [{ item: { codigo: 'BLCS.PTO.G1' } }], + ...overrides + } + } + } + }; +} + +export function tinyError(codigo: string, erro: string) { + return { data: { retorno: { status: 'Erro', codigo_erro: codigo, erros: [{ erro }] } } }; +} + +export function axiosError(code: string, status?: number) { + const error: any = new Error(status ? `Request failed with status code ${status}` : code); + error.code = code; + if (status) error.response = { status, data: {} }; + return error; +} + +export const fakeRes = () => ({ status() { return this; }, send() { return this; }, json() { return this; } }) as any; + +export const orderWebhook = (id: string | number, codigoSituacao: string, descricaoSituacao: string) => ({ + query: {}, + body: { dados: { id, codigoSituacao, descricaoSituacao } } +}) as any; + +export const isTinyCall = (url: string) => url.includes('api.tiny.com.br'); + +export function silenceConsole() { + const original = { log: console.log, warn: console.warn, error: console.error }; + const warnings: string[] = []; + console.log = () => {}; + console.warn = (...args: any[]) => { warnings.push(args.join(' ')); }; + console.error = (...args: any[]) => { warnings.push(args.join(' ')); }; + return { warnings, restore: () => Object.assign(console, original) }; +} diff --git a/test/live-queue.test.ts b/test/live-queue.test.ts new file mode 100644 index 0000000..52ee2ea --- /dev/null +++ b/test/live-queue.test.ts @@ -0,0 +1,27 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers'; + +// Real spacing between Olist calls, default max queue wait. +setTestEnv({ TINY_LIVE_REQUEST_DELAY_MS: '250' }); +const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller'); + +const calls = mockAxiosPost(async (url, data) => { + if (!isTinyCall(url)) return { status: 200, data: {} }; + return tinyOrder(new URLSearchParams(data.toString()).get('id')!); +}); + +test('a burst of webhooks is queued and every order is forwarded with Olist data', async () => { + const capture = silenceConsole(); + try { + const ids = [1, 2, 3, 4, 5, 6, 7, 8].map(i => 2000 + i); + await Promise.all(ids.map(id => handleTinyOrderUpdate(orderWebhook(id, 'pronto_envio', 'Pronto para envio'), fakeRes()))); + + const forwarded = calls.filter(c => !isTinyCall(c.url)).map(c => c.data); + assert.equal(forwarded.length, ids.length); + assert.ok(forwarded.every(p => p.fone && p.forma_envio === 'X'), 'every order keeps phone and forma_envio'); + assert.ok(!capture.warnings.some(w => w.includes('too busy')), 'no order skipped the Olist lookup'); + } finally { + capture.restore(); + } +}); diff --git a/test/n8n-service.test.ts b/test/n8n-service.test.ts new file mode 100644 index 0000000..97e8e32 --- /dev/null +++ b/test/n8n-service.test.ts @@ -0,0 +1,51 @@ +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { setTestEnv, mockAxiosPost, axiosError, silenceConsole } from './helpers'; + +setTestEnv({}); +const { sendToN8n } = require('../src/services/n8n.service'); + +let responses: Array<() => any> = []; +const calls = mockAxiosPost(async () => { + const next = responses.shift(); + return next ? next() : { status: 200, data: {} }; +}); + +let capture: ReturnType; +before(() => { capture = silenceConsole(); }); +after(() => capture.restore()); +beforeEach(() => { calls.length = 0; responses = []; }); + +const fail = (code: string, status?: number) => () => { throw axiosError(code, status); }; + +test('retries when n8n refuses the connection (n8n restarting)', async () => { + responses = [fail('ECONNREFUSED')]; + await sendToN8n({ id: 1 }, 'http://n8n.test/status'); + assert.equal(calls.length, 2); +}); + +test('retries when the proxy says n8n is down (502/503)', async () => { + responses = [fail('ERR_BAD_RESPONSE', 502), fail('ERR_BAD_RESPONSE', 503)]; + await sendToN8n({ id: 1 }, 'http://n8n.test/status'); + assert.equal(calls.length, 3); +}); + +test('retries 404 while n8n has not registered the webhook yet, up to the max attempts', async () => { + responses = [1, 2, 3, 4, 5, 6].map(() => fail('ERR_BAD_REQUEST', 404)); + await sendToN8n({ id: 1 }, 'http://n8n.test/status'); + assert.equal(calls.length, 5); +}); + +test('does not retry when n8n may already have received the request', async () => { + for (const failure of [fail('ECONNABORTED'), fail('ECONNRESET'), fail('ERR_BAD_RESPONSE', 504), fail('ERR_BAD_RESPONSE', 500), fail('ERR_BAD_REQUEST', 400)]) { + calls.length = 0; + responses = [failure]; + await sendToN8n({ id: 1 }, 'http://n8n.test/status'); + assert.equal(calls.length, 1); + } +}); + +test('sends once when n8n answers', async () => { + await sendToN8n({ id: 1 }, 'http://n8n.test/status'); + assert.equal(calls.length, 1); +}); diff --git a/test/order-webhook.test.ts b/test/order-webhook.test.ts new file mode 100644 index 0000000..d85298b --- /dev/null +++ b/test/order-webhook.test.ts @@ -0,0 +1,102 @@ +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 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; +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); +}); diff --git a/test/stock-and-shutdown.test.ts b/test/stock-and-shutdown.test.ts new file mode 100644 index 0000000..31d76a0 --- /dev/null +++ b/test/stock-and-shutdown.test.ts @@ -0,0 +1,67 @@ +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' }); +const { handleTinyStockUpdate } = require('../src/controllers/webhook.controller'); +const webhookRoutes = require('../src/routes/webhook.route'); + +const calls = mockAxiosPost(async (url, data) => { + if (!isTinyCall(url)) return { status: 200, data: {} }; + return tinyOrder(new URLSearchParams(data.toString()).get('id')!); +}); + +const capture = silenceConsole(); +after(() => { + capture.restore(); + fs.rmSync(runtimeDir, { recursive: true, force: true }); +}); + +const stockWebhook = (saldo: number) => ({ query: {}, body: { dados: { idProduto: '555', nome: 'Camiseta', saldo } } }) as any; + +test('stock memory and CSV are written to the persistent runtime directory', async () => { + await handleTinyStockUpdate(stockWebhook(10), fakeRes()); + await handleTinyStockUpdate(stockWebhook(25), fakeRes()); + + const memory = JSON.parse(fs.readFileSync(path.join(runtimeDir, 'stock_memory.json'), 'utf-8')); + assert.equal(memory['555'].saldo, 25); + assert.ok(fs.readFileSync(path.join(runtimeDir, 'stock_log.csv'), 'utf-8').includes('"555","Camiseta","10","25","15"')); + + const forwarded = calls.filter(c => c.url === 'http://n8n.test/stock').map(c => c.data.dados); + assert.equal(forwarded[1].delta_estoque, 15); +}); + +test('draining on shutdown waits for webhooks that were acked but still queued', async () => { + const app = express(); + app.use(express.json()); + app.use('/api/webhooks', webhookRoutes.default); + const server = app.listen(0); + const { port } = server.address() as AddressInfo; + + try { + const ids = [3001, 3002, 3003]; + for (const id of ids) { + const res = await fetch(`http://127.0.0.1:${port}/api/webhooks/tiny/order-status`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ dados: { id, codigoSituacao: 'pronto_envio', descricaoSituacao: 'Pronto para envio' } }) + }); + assert.equal(res.status, 200); + } + + const forwardedBefore = calls.filter(c => c.url === 'http://n8n.test/status').length; + assert.ok(forwardedBefore < ids.length, 'some orders are still queued when shutdown starts'); + + const remaining = await webhookRoutes.drainWebhookWork(10000); + assert.equal(remaining, 0); + assert.equal(calls.filter(c => c.url === 'http://n8n.test/status').length, ids.length); + } finally { + server.close(); + } +});