Compare commits

...

4 Commits

Author SHA1 Message Date
Cauê Faleiros
64aa0a6338 Fill Jadlog tracking codes from the MULTI EMPRESAS account
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m53s
Jadlog orders are invoiced by the MULTI EMPRESAS Olist account, so our
order reaches "Enviado" with forma_envio J and an empty tracking code.
When TINY_API_TOKEN_MULTI is set, shipped Jadlog orders without tracking
are matched in that account (search by customer CPF/name from the order
date, confirmed by numero_ordem_compra) and the code is forwarded in
codigo_rastreamento. Calls are serialized and cached; any failure keeps
today's payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:24:01 -03:00
Cauê Faleiros
e204135eb6 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>
2026-10-08 15:30:38 -03:00
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
21 changed files with 1075 additions and 144 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

@@ -16,6 +16,8 @@ services:
- TINY_WEBHOOK_SECRET=${TINY_WEBHOOK_SECRET}
- N8N_AUTH_TOKEN=${N8N_AUTH_TOKEN}
- TINY_API_TOKEN=${TINY_API_TOKEN}
# Token of the MULTI EMPRESAS Olist account, where Jadlog tracking codes live.
- TINY_API_TOKEN_MULTI=${TINY_API_TOKEN_MULTI}
- GRAPHS_API_URL=${GRAPHS_API_URL}
- GRAPHS_API_KEY=${GRAPHS_API_KEY}
- GRAPHS_BACKFILL_CONTACT_FALLBACK=${GRAPHS_BACKFILL_CONTACT_FALLBACK:-true}
@@ -48,6 +50,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

@@ -1,10 +1,17 @@
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 { needsMultiTracking, findMultiTracking } from '../services/multi-tracking.service';
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 +37,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 +118,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 +163,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');
@@ -195,6 +242,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
@@ -252,6 +325,15 @@ 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.`);
}
let codigoRastreamento = fullOrderDetails?.codigo_rastreamento || "";
if (needsMultiTracking(fullOrderDetails)) {
codigoRastreamento = await findMultiTracking(String(orderId), fullOrderDetails);
}
// Build the exact flat JSON payload requested by the user
const finalPayload = {
id: fullOrderDetails?.id || payload.dados?.id || "",
@@ -269,7 +351,7 @@ export const handleTinyOrderUpdate = async (req: Request, res: Response): Promis
email: fullOrderDetails?.cliente?.email || "",
status_processamento: statusProcessamento,
forma_envio: fullOrderDetails?.forma_envio || "",
codigo_rastreamento: fullOrderDetails?.codigo_rastreamento || "",
codigo_rastreamento: codigoRastreamento,
url_rastreamento: fullOrderDetails?.url_rastreamento || "",
itens: fullOrderDetails?.itens || [] // Added so n8n can filter specific products!
};
@@ -282,11 +364,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) {
@@ -333,7 +415,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 +487,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

@@ -0,0 +1,156 @@
import axios from 'axios';
// Jadlog orders are invoiced by the MULTI EMPRESAS Olist account, so the tracking code
// only exists there. The MULTI order keeps our order's e-commerce number in its
// numero_ordem_compra, which pedidos.pesquisa can't filter by: we search that account by
// customer and order date, then confirm the match with pedido.obter.
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 JADLOG_FORMA_ENVIO = 'J';
const LOOKUP_STATUSES = new Set(['enviado']);
// Spacing between calls on the MULTI account, which has its own rate limit and other users.
const REQUEST_DELAY_MS = numberEnv('MULTI_TINY_REQUEST_DELAY_MS', 2000);
const RETRY_DELAY_MS = numberEnv('MULTI_TINY_RETRY_DELAY_MS', 30000);
const REQUEST_TIMEOUT_MS = numberEnv('TINY_REQUEST_TIMEOUT_MS', 20000);
const MAX_ATTEMPTS = 2;
const MAX_CANDIDATES = 5;
const FOUND_TTL_MS = 24 * 60 * 60 * 1000;
const NOT_FOUND_TTL_MS = 10 * 60 * 1000;
const RETRYABLE_ERROR_CODES = new Set(['6', '11', '35', '99']);
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const results = new Map<string, { tracking: string; expiresAt: number }>();
const inFlight = new Map<string, Promise<string>>();
let queueTail: Promise<void> = Promise.resolve();
let nextRequestAt = 0;
function multiToken() {
return (process.env.TINY_API_TOKEN_MULTI || '').trim();
}
export function needsMultiTracking(order: any): boolean {
return Boolean(
multiToken() &&
order &&
String(order.forma_envio || '').trim().toUpperCase() === JADLOG_FORMA_ENVIO &&
!String(order.codigo_rastreamento || '').trim() &&
LOOKUP_STATUSES.has(String(order.situacao || '').trim().toLowerCase())
);
}
// One request at a time, spaced, so webhook bursts don't trip the MULTI rate limit.
function queued<T>(operation: () => Promise<T>): Promise<T> {
const run = queueTail.catch(() => undefined).then(async () => {
const waitMs = Math.max(0, nextRequestAt - Date.now());
if (waitMs > 0) await sleep(waitMs);
nextRequestAt = Date.now() + REQUEST_DELAY_MS;
return operation();
});
queueTail = run.then(() => undefined, () => undefined);
return run;
}
async function multiPost(servicePhp: string, params: Record<string, string>): Promise<any> {
for (let attempt = 1; ; attempt++) {
const response = await queued(() => axios.post(
`https://api.tiny.com.br/api2/${servicePhp}`,
new URLSearchParams({ token: multiToken(), formato: 'JSON', ...params }),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: REQUEST_TIMEOUT_MS }
));
const retorno = response.data?.retorno;
const errorCode = String(retorno?.codigo_erro ?? '');
if (retorno?.status === 'OK' || !RETRYABLE_ERROR_CODES.has(errorCode) || attempt >= MAX_ATTEMPTS) {
return retorno;
}
console.warn(`[Jadlog tracking] MULTI ${servicePhp} returned codigo_erro ${errorCode}. Retrying in ${RETRY_DELAY_MS}ms.`);
await sleep(RETRY_DELAY_MS);
}
}
function matchKeys(order: any): Set<string> {
return new Set(
[order.numero_ordem_compra, order.numero_ecommerce, order.ecommerce?.numeroPedidoEcommerce]
.map(value => String(value || '').trim())
.filter(Boolean)
);
}
async function searchCandidates(order: any): Promise<any[]> {
const dataInicial = String(order.data_pedido || '').trim();
const dateFilter: Record<string, string> = dataInicial ? { dataInicial } : {};
const filters: Record<string, string>[] = [];
const cpfCnpj = String(order.cliente?.cpf_cnpj || '').trim();
const nome = String(order.cliente?.nome || '').trim();
if (cpfCnpj) filters.push({ cpf_cnpj: cpfCnpj });
if (nome) filters.push({ cliente: nome });
for (const filter of filters) {
const retorno = await multiPost('pedidos.pesquisa.php', { ...filter, ...dateFilter, sort: 'DESC' });
const pedidos = (retorno?.pedidos || []).map((entry: any) => entry.pedido).filter(Boolean);
if (pedidos.length) {
// Orders that already carry a tracking code are the likely match; check them first.
return pedidos.sort((a: any, b: any) => Number(Boolean(b.codigo_rastreamento)) - Number(Boolean(a.codigo_rastreamento)));
}
}
return [];
}
async function lookup(orderId: string, order: any): Promise<string> {
const keys = matchKeys(order);
if (!keys.size) {
console.warn(`[Jadlog tracking] Order ID ${orderId} has no e-commerce number to match in MULTI EMPRESAS.`);
return '';
}
const candidates = await searchCandidates(order);
for (const candidate of candidates.slice(0, MAX_CANDIDATES)) {
const retorno = await multiPost('pedido.obter.php', { id: String(candidate.id) });
const multiOrder = retorno?.pedido;
if (!multiOrder) continue;
const multiKeys = matchKeys(multiOrder);
if (![...keys].some(key => multiKeys.has(key))) continue;
const tracking = String(multiOrder.codigo_rastreamento || '').trim();
console.log(`[Jadlog tracking] Order ID ${orderId} matched MULTI EMPRESAS order ${multiOrder.numero}: ${tracking ? 'tracking found' : 'no tracking code yet'}.`);
return tracking;
}
console.warn(`[Jadlog tracking] Order ID ${orderId} (${[...keys].join(', ')}) was not found in MULTI EMPRESAS (${candidates.length} candidate(s) checked).`);
return '';
}
// Never throws: if MULTI EMPRESAS can't be reached the order goes out as it does today, without tracking.
export async function findMultiTracking(orderId: string, order: any): Promise<string> {
const now = Date.now();
for (const [key, cached] of results) {
if (now > cached.expiresAt) results.delete(key);
}
const cached = results.get(orderId);
if (cached) return cached.tracking;
const existing = inFlight.get(orderId);
if (existing) return existing;
const promise = lookup(orderId, order)
.then(tracking => {
results.set(orderId, { tracking, expiresAt: Date.now() + (tracking ? FOUND_TTL_MS : NOT_FOUND_TTL_MS) });
return tracking;
})
.catch((error: any) => {
console.error(`[Jadlog tracking] MULTI EMPRESAS lookup failed for Order ID ${orderId}: ${error.code || error.message}`);
return '';
})
.finally(() => inFlight.delete(orderId));
inFlight.set(orderId, promise);
return promise;
}

View File

@@ -1,35 +1,74 @@
import axios from 'axios';
export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<void> => {
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));
// 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;
}
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 true;
} 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 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));
}

93
test/helpers.ts Normal file
View File

@@ -0,0 +1,93 @@
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.
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, {
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',
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) };
}

View File

@@ -0,0 +1,164 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import { setTestEnv, mockAxiosPost, tinyOrder, tinyError, axiosError, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers';
setTestEnv({ TINY_API_TOKEN_MULTI: 'multi-token', MULTI_TINY_REQUEST_DELAY_MS: '0', MULTI_TINY_RETRY_DELAY_MS: '5' });
const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller');
// NexStar side: the order as our account sees it (Jadlog, shipped, no tracking).
const nexstarOrders: Record<string, Record<string, any>> = {};
const jadlogOrder = (ecommerce: string, overrides: Record<string, any> = {}) => ({
forma_envio: 'J',
situacao: 'Enviado',
numero_ecommerce: ecommerce,
numero_ordem_compra: ecommerce,
data_pedido: '18/11/2026',
cliente: { nome: 'Cliente Jadlog', celular: '(16) 99999-0000', cpf_cnpj: '123.456.789-00' },
...overrides
});
// MULTI EMPRESAS side: our e-commerce number only shows up in numero_ordem_compra.
let multiSearch: (params: URLSearchParams) => any = () => tinyError('20', 'A consulta não retornou registros');
const multiOrders: Record<string, () => any> = {};
const multiOrder = (id: string, numero: string, ordemCompra: string, tracking: string) => ({
data: { retorno: { status: 'OK', pedido: { id, numero, numero_ecommerce: null, numero_ordem_compra: ordemCompra, forma_envio: 'J', codigo_rastreamento: tracking } } }
});
const multiList = (...pedidos: Array<{ id: string; codigo_rastreamento?: string }>) => ({
data: { retorno: { status: 'OK', pedidos: pedidos.map(pedido => ({ pedido })) } }
});
const calls = mockAxiosPost(async (url, data) => {
if (!isTinyCall(url)) return { status: 200, data: {} };
const params = new URLSearchParams(data.toString());
if (params.get('token') === 'multi-token') {
if (url.endsWith('pedidos.pesquisa.php')) return multiSearch(params);
const response = multiOrders[params.get('id')!];
return response ? response() : tinyError('32', 'Pedido não localizado');
}
const id = params.get('id')!;
return tinyOrder(id, nexstarOrders[id]);
});
const multiCalls = () => calls.filter(c => isTinyCall(c.url) && new URLSearchParams(c.data.toString()).get('token') === 'multi-token');
const forwarded = (id: string) => calls.filter(c => c.url === 'http://n8n.test/status' && String(c.data.id) === id).map(c => c.data);
const shipped = (id: string) => handleTinyOrderUpdate(orderWebhook(id, 'enviado', 'Enviado'), 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 shipped Jadlog order gets the tracking code from MULTI EMPRESAS, everything else unchanged', async () => {
nexstarOrders['5001'] = jadlogOrder('865864C549');
let searched: URLSearchParams | undefined;
multiSearch = params => { searched = params; return multiList({ id: '9001', codigo_rastreamento: '14676700000182' }); };
multiOrders['9001'] = () => multiOrder('9001', '12749', '865864C549', '14676700000182');
await shipped('5001');
const [payload] = forwarded('5001');
assert.equal(payload.codigo_rastreamento, '14676700000182');
assert.equal(payload.forma_envio, 'J');
assert.equal(payload.numero, '140255');
assert.equal(payload.numero_ecommerce, '865864C549');
assert.equal(payload.fone, '(16) 99999-0000');
assert.equal(searched?.get('cpf_cnpj'), '123.456.789-00');
assert.equal(searched?.get('dataInicial'), '18/11/2026');
});
test('only the MULTI order with our number in its purchase order is used, not other orders of the same customer', async () => {
nexstarOrders['5002'] = jadlogOrder('AAAA000002');
multiSearch = () => multiList({ id: '9002', codigo_rastreamento: '111' }, { id: '9003', codigo_rastreamento: '222' });
multiOrders['9002'] = () => multiOrder('9002', '12800', 'OTHER00001', '111');
multiOrders['9003'] = () => multiOrder('9003', '12801', 'AAAA000002', '222');
await shipped('5002');
assert.equal(forwarded('5002')[0].codigo_rastreamento, '222');
});
test('falls back to searching by customer name when the CPF search finds nothing', async () => {
nexstarOrders['5003'] = jadlogOrder('AAAA000003');
multiSearch = params => params.get('cliente') === 'Cliente Jadlog' ? multiList({ id: '9004' }) : tinyError('20', 'A consulta não retornou registros');
multiOrders['9004'] = () => multiOrder('9004', '12802', 'AAAA000003', '333');
await shipped('5003');
assert.equal(forwarded('5003')[0].codigo_rastreamento, '333');
});
test('other carriers, Jadlog before shipping, and orders that already have tracking never call MULTI EMPRESAS', async () => {
const before = multiCalls().length;
nexstarOrders['5004'] = { forma_envio: 'C', situacao: 'Enviado', codigo_rastreamento: 'QB123BR' };
nexstarOrders['5005'] = { forma_envio: 'X', situacao: 'Enviado' };
nexstarOrders['5006'] = jadlogOrder('AAAA000006', { situacao: 'Pronto para envio' });
nexstarOrders['5007'] = jadlogOrder('AAAA000007', { codigo_rastreamento: 'JD999' });
await shipped('5004');
await shipped('5005');
await handleTinyOrderUpdate(orderWebhook('5006', 'pronto_envio', 'Pronto para envio'), fakeRes());
await shipped('5007');
assert.equal(multiCalls().length, before);
assert.equal(forwarded('5004')[0].codigo_rastreamento, 'QB123BR');
assert.equal(forwarded('5007')[0].codigo_rastreamento, 'JD999');
});
test('when MULTI EMPRESAS fails or has no match the order is still forwarded, just without tracking', async () => {
nexstarOrders['5008'] = jadlogOrder('AAAA000008');
multiSearch = () => { throw axiosError('ECONNABORTED'); };
await shipped('5008');
nexstarOrders['5009'] = jadlogOrder('AAAA000009');
multiSearch = () => tinyError('20', 'A consulta não retornou registros');
await shipped('5009');
for (const id of ['5008', '5009']) {
const [payload] = forwarded(id);
assert.equal(payload.codigo_rastreamento, '');
assert.equal(payload.forma_envio, 'J');
assert.equal(payload.situacao, 'Enviado');
}
});
test('retries once when MULTI EMPRESAS rate-limits the search', async () => {
nexstarOrders['5010'] = jadlogOrder('AAAA000010');
let searches = 0;
multiSearch = () => (++searches === 1 ? tinyError('6', 'API bloqueada') : multiList({ id: '9010' }));
multiOrders['9010'] = () => multiOrder('9010', '12810', 'AAAA000010', '1010');
await shipped('5010');
assert.equal(searches, 2);
assert.equal(forwarded('5010')[0].codigo_rastreamento, '1010');
});
test('repeated webhooks for the same shipped order reuse the tracking found, without new MULTI calls', async () => {
nexstarOrders['5011'] = jadlogOrder('AAAA000011');
multiSearch = () => multiList({ id: '9011' });
multiOrders['9011'] = () => multiOrder('9011', '12811', 'AAAA000011', '1111');
await shipped('5011');
const after = multiCalls().length;
await Promise.all([shipped('5011'), shipped('5011')]);
assert.equal(multiCalls().length, after);
});
test('without TINY_API_TOKEN_MULTI nothing changes', async () => {
const token = process.env.TINY_API_TOKEN_MULTI;
delete process.env.TINY_API_TOKEN_MULTI;
try {
const before = multiCalls().length;
nexstarOrders['5012'] = jadlogOrder('AAAA000012');
await shipped('5012');
assert.equal(multiCalls().length, before);
assert.equal(forwarded('5012')[0].codigo_rastreamento, '');
} finally {
process.env.TINY_API_TOKEN_MULTI = token;
}
});

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

@@ -0,0 +1,66 @@
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import path from 'path';
import express from 'express';
import { AddressInfo } from 'net';
import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, isTinyCall, silenceConsole } from './helpers';
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');
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();
}
});