Compare commits

...

2 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
10 changed files with 559 additions and 13 deletions

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}

View File

@@ -1,6 +1,8 @@
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';
@@ -240,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
@@ -301,6 +329,11 @@ export const handleTinyOrderUpdate = async (req: Request, res: Response): Promis
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 || "",
@@ -318,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!
};
@@ -331,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) {

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

@@ -26,13 +26,14 @@ function isSafeToRetry(error: any): boolean {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<void> => {
// 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;
}
const headers: Record<string, string> = {
@@ -51,7 +52,7 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<v
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;
return true;
} catch (error: any) {
const reason = error.response ? `HTTP ${error.response.status}` : (error.code || error.message);
@@ -66,7 +67,8 @@ export const sendToN8n = async (data: any, targetWebhookUrl?: string): Promise<v
if (error.response) {
console.error('n8n Response:', error.response.status, error.response.data);
}
return;
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));
}

View File

@@ -1,4 +1,7 @@
import axios from 'axios';
import fs from 'fs';
import os from 'os';
import path from 'path';
// Each test file runs in its own process; set env before requiring app modules,
// since they read their config at load time.
@@ -9,6 +12,7 @@ export function setTestEnv(overrides: Record<string, string>) {
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',

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

View File

@@ -50,13 +50,13 @@ test('a status change minutes later refetches instead of reusing the old status'
assert.equal(tinyCallsFor('1002').length, 2);
});
test('a same-status duplicate webhook reuses the cached lookup', async () => {
test('a same-status duplicate webhook reuses the cached lookup and is not sent to n8n again', async () => {
tinyResponses['1003'] = [() => tinyOrder('1003')];
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1003').length, 1);
assert.equal(forwardedFor('1003').length, 2);
assert.equal(forwardedFor('1003').length, 1);
});
test('retries when Olist rate-limits the lookup (codigo_erro 6)', async () => {

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

@@ -1,14 +1,13 @@
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import express from 'express';
import { AddressInfo } from 'net';
import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, isTinyCall, silenceConsole } from './helpers';
const runtimeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tiny-webhook-test-'));
setTestEnv({ RUNTIME_DATA_DIR: runtimeDir, N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' });
setTestEnv({ N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' });
const runtimeDir = process.env.RUNTIME_DATA_DIR!;
const { handleTinyStockUpdate } = require('../src/controllers/webhook.controller');
const webhookRoutes = require('../src/routes/webhook.route');