Compare commits

...

2 Commits

Author SHA1 Message Date
Cauê Faleiros
c5e168429d Make builds reproducible and redeploys graceful
All checks were successful
Build and Deploy / build-and-push (push) Successful in 43s
- Install with npm ci from package-lock.json so a rebuild can't pull
  different dependency versions than were tested.
- Run node directly (not via npm) so it receives SIGTERM and can drain
  queued webhooks; give the stack a 60s stop_grace_period and start the
  new task before stopping the old one.
- Add .dockerignore and stop tracking dist/ (already gitignored and
  rebuilt by the Dockerfile).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:12:09 -03:00
Cauê Faleiros
4fe5830f8f Stop losing notifications on Olist/n8n hiccups and redeploys
- Olist lookups: 20s timeout so one hung request can't stall the serial
  queue; retry temporary failures (codigo_erro 6/11/35/99, timeouts,
  5xx) with backoff instead of forwarding orders without phone or
  forma_envio. Log "[Notification at risk]" when that still happens.
- n8n forwarding: timeout plus retries, only when n8n certainly didn't
  run the workflow (connection refused, 502/503, 404 while restarting),
  so retries can't send a customer the same WhatsApp twice. Stop logging
  the start of N8N_AUTH_TOKEN.
- On SIGTERM, stop accepting requests and finish webhooks already acked
  to Tiny (up to SHUTDOWN_GRACE_MS, default 50s).
- Keep stock_memory.json and stock_log.csv on the data-runtime volume so
  stock stats survive redeploys.
- Add a node:test suite (npm test) covering the payload n8n reads, the
  status cache, burst queueing, retries, stock files and shutdown drain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:12:09 -03:00
17 changed files with 523 additions and 138 deletions

9
.dockerignore Normal file
View File

@@ -0,0 +1,9 @@
node_modules
dist
.env
.git
data-runtime
graphs-temp
*.php
NexStar*.json
caue-teste-tiny.json

View File

@@ -3,9 +3,9 @@ FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files and install all dependencies (including devDependencies for TypeScript)
COPY package.json ./
RUN npm install
# Copy package files and install the exact locked dependencies (including devDependencies for TypeScript)
COPY package.json package-lock.json ./
RUN npm ci
# Copy source code and build
COPY . .
@@ -16,9 +16,9 @@ FROM node:20-alpine
WORKDIR /app
# Copy package files and install ONLY production dependencies
COPY package.json ./
RUN npm install --omit=dev
# Copy package files and install ONLY the locked production dependencies
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
# Copy built code from the builder stage
COPY --from=builder /app/dist ./dist
@@ -27,5 +27,5 @@ COPY --from=builder /app/data ./data
# Expose the port the app runs on
EXPOSE 3000
# Command to run the application
CMD ["npm", "start"]
# Run node directly so it receives SIGTERM on redeploy and can finish queued webhooks
CMD ["node", "dist/index.js"]

View File

@@ -1,40 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleTinyOrderUpdate = void 0;
const n8n_service_1 = require("../services/n8n.service");
const handleTinyOrderUpdate = async (req, res) => {
try {
let payload = req.body;
// Parse 'dados' if it comes as a JSON string
if (typeof payload.dados === 'string') {
try {
payload.dados = JSON.parse(payload.dados);
}
catch (e) {
console.error('Could not parse "dados" as JSON string.', e);
}
}
console.log('Received webhook from Tiny:', JSON.stringify(payload, null, 2));
// Acknowledge Tiny immediately
res.status(200).send('OK');
if (!payload || Object.keys(payload).length === 0) {
console.warn('Received empty payload from Tiny webhook.');
return;
}
const transformedData = {
source: 'tiny_webhook_middleware',
event: payload.tipo || 'atualizacao_pedido',
dados: payload.dados,
raw_payload: payload
};
// Forward to n8n asynchronously
await (0, n8n_service_1.sendToN8n)(transformedData);
}
catch (error) {
console.error('Error handling Tiny webhook:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Internal server error processing webhook.' });
}
}
};
exports.handleTinyOrderUpdate = handleTinyOrderUpdate;

20
dist/index.js vendored
View File

@@ -1,20 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const dotenv_1 = __importDefault(require("dotenv"));
const webhook_route_1 = __importDefault(require("./routes/webhook.route"));
dotenv_1.default.config();
const app = (0, express_1.default)();
const port = process.env.PORT || 3000;
app.use(express_1.default.json());
app.use(express_1.default.urlencoded({ extended: true }));
app.use('/api/webhooks', webhook_route_1.default);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK', message: 'Tiny-n8n middleware is running.' });
});
app.listen(port, () => {
console.log(`[server]: Middleware server is running at http://localhost:${port}`);
});

View File

@@ -1,7 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const webhook_controller_1 = require("../controllers/webhook.controller");
const router = (0, express_1.Router)();
router.post('/tiny/order-status', webhook_controller_1.handleTinyOrderUpdate);
exports.default = router;

View File

@@ -1,30 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendToN8n = void 0;
const axios_1 = __importDefault(require("axios"));
const sendToN8n = async (data) => {
const n8nWebhookUrl = process.env.N8N_WEBHOOK_URL;
if (!n8nWebhookUrl) {
console.error('N8N_WEBHOOK_URL is not defined in environment variables.');
return;
}
try {
console.log(`Forwarding payload to n8n at ${n8nWebhookUrl}...`);
const response = await axios_1.default.post(n8nWebhookUrl, data, {
headers: {
'Content-Type': 'application/json'
}
});
console.log(`Successfully forwarded to n8n. Status: ${response.status}`);
}
catch (error) {
console.error('Failed to forward payload to n8n.', error.message);
if (error.response) {
console.error('n8n Response:', error.response.status, error.response.data);
}
}
};
exports.sendToN8n = sendToN8n;

View File

@@ -48,6 +48,12 @@ services:
# - nginx-proxy-manager-network
volumes:
- middleware_data:/app/data-runtime
# Give the app time to finish queued webhooks on redeploy (SHUTDOWN_GRACE_MS is 50s).
stop_grace_period: 60s
deploy:
update_config:
# Start the new task before stopping the old one so webhooks keep landing during a redeploy.
order: start-first
# networks:
# nginx-proxy-manager-network:

View File

@@ -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": "",

View File

@@ -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<void> = Promise.resolve();
let liveTinyNextRequestAt = 0;
let liveTinyPendingRequests = 0;
@@ -105,10 +116,44 @@ async function runWithLiveTinySlot<T>(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<OrderDetailsResult | null> {
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<string, any> = {};
// 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';

View File

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

View File

@@ -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<Promise<void>>();
export default router;
const tracked = (handler: (req: Request, res: Response) => Promise<void>) => (req: Request, res: Response) => {
const work: Promise<void> = 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<number> {
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<void>(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;

View File

@@ -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<void> => {
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<v
return;
}
try {
console.log(`Forwarding payload to n8n at ${n8nWebhookUrl}...`);
const headers: Record<string, string> = {
'Content-Type': 'application/json'
};
const headers: Record<string, string> = {
'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;
}
}
};

89
test/helpers.ts Normal file
View File

@@ -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<string, string>) {
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<any>;
// 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<string, any> = {}) {
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) };
}

27
test/live-queue.test.ts Normal file
View File

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

51
test/n8n-service.test.ts Normal file
View File

@@ -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<typeof silenceConsole>;
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);
});

102
test/order-webhook.test.ts Normal file
View File

@@ -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<string, Array<() => 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<typeof silenceConsole>;
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);
});

View File

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