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>
This commit is contained in:
Cauê Faleiros
2026-11-19 13:24:01 -03:00
parent e204135eb6
commit 64aa0a6338
4 changed files with 329 additions and 1 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

@@ -2,6 +2,7 @@ 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';
@@ -328,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 || "",
@@ -345,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!
};

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

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