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>
157 lines
6.6 KiB
TypeScript
157 lines
6.6 KiB
TypeScript
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;
|
|
}
|