diff --git a/src/controllers/webhook.controller.ts b/src/controllers/webhook.controller.ts index b4de55d..86cb999 100644 --- a/src/controllers/webhook.controller.ts +++ b/src/controllers/webhook.controller.ts @@ -152,10 +152,18 @@ async function fetchOrderDetailsFromTiny(orderId: string, tinyApiToken: string): }; } -async function getOrFetchOrderDetails(orderId: string, tinyApiToken: string): Promise { - const cachedDetails = getCachedOrderDetails(orderId); +// Cache per order *and* status: Tiny fires one webhook per status change, often seconds +// apart (e.g. "Preparando envio" -> "Pronto para envio"), and a cache keyed only by order +// would forward the previous status. Same-status duplicates still share one fetch. +function orderDetailsCacheKey(orderId: string, webhookStatus: string) { + return `${orderId}:${webhookStatus}`; +} + +async function getOrFetchOrderDetails(orderId: string, webhookStatus: string, tinyApiToken: string): Promise { + const cacheKey = orderDetailsCacheKey(orderId, webhookStatus); + const cachedDetails = getCachedOrderDetails(cacheKey); if (cachedDetails) { - console.log(`Using cached order details for Order ID: ${orderId}.`); + console.log(`Using cached order details for Order ID: ${orderId} (status ${webhookStatus || 'unknown'}).`); return { fullOrderDetails: cachedDetails.fullOrderDetails, statusProcessamento: cachedDetails.statusProcessamento, @@ -163,24 +171,24 @@ async function getOrFetchOrderDetails(orderId: string, tinyApiToken: string): Pr }; } - const existingFetch = inFlightOrderDetails.get(orderId); + const existingFetch = inFlightOrderDetails.get(cacheKey); if (existingFetch) { - console.log(`Waiting for in-flight Tiny fetch for Order ID: ${orderId}.`); + console.log(`Waiting for in-flight Tiny fetch for Order ID: ${orderId} (status ${webhookStatus || 'unknown'}).`); return existingFetch; } const fetchPromise = fetchOrderDetailsFromTiny(orderId, tinyApiToken) .then(result => { if (result) { - setCachedOrderDetails(orderId, result); + setCachedOrderDetails(cacheKey, result); } return result; }) .finally(() => { - inFlightOrderDetails.delete(orderId); + inFlightOrderDetails.delete(cacheKey); }); - inFlightOrderDetails.set(orderId, fetchPromise); + inFlightOrderDetails.set(cacheKey, fetchPromise); return fetchPromise; } @@ -223,7 +231,8 @@ export const handleTinyOrderUpdate = async (req: Request, res: Response): Promis if (tinyApiToken) { try { - const details = await getOrFetchOrderDetails(String(orderId), tinyApiToken); + const webhookStatus = String(payload.dados?.codigoSituacao || payload.dados?.descricaoSituacao || '').trim(); + const details = await getOrFetchOrderDetails(String(orderId), webhookStatus, tinyApiToken); if (details) { fullOrderDetails = details.fullOrderDetails; statusProcessamento = details.statusProcessamento;