diff --git a/src/controllers/webhook.controller.ts b/src/controllers/webhook.controller.ts index 0c00342..9a60f75 100644 --- a/src/controllers/webhook.controller.ts +++ b/src/controllers/webhook.controller.ts @@ -1,6 +1,8 @@ import { Request, Response } from 'express'; import { sendToN8n } from '../services/n8n.service'; import axios from 'axios'; +import fs from 'fs'; +import path from 'path'; export const handleTinyOrderUpdate = async (req: Request, res: Response): Promise => { try { @@ -156,12 +158,53 @@ export const handleTinyStockUpdate = async (req: Request, res: Response): Promis return; } - console.log('Received stock webhook from Tiny. Forwarding to n8n...'); + console.log('Received stock webhook from Tiny. Calculating delta...'); let payload = req.body || {}; if (payload && typeof payload.dados === 'string') { try { payload.dados = JSON.parse(payload.dados); } catch (e) {} } + // --- SMART MEMORY LOGIC --- + const memoryFile = path.join(process.cwd(), 'stock_memory.json'); + let memory: Record = {}; + + // Load memory if it exists + if (fs.existsSync(memoryFile)) { + try { + memory = JSON.parse(fs.readFileSync(memoryFile, 'utf-8')); + } catch (e) { + console.error("Failed to parse stock_memory.json, starting fresh."); + } + } + + const dados = payload.dados || {}; + const idProduto = String(dados.idProduto || dados.id || ""); + const novoSaldo = Number(dados.saldo || 0); + + let deltaEstoque = 0; + + if (idProduto) { + const estoqueAntigo = memory[idProduto]; + + if (estoqueAntigo !== undefined) { + // We know what it was before, calculate the difference + deltaEstoque = novoSaldo - estoqueAntigo; + } else { + // First time seeing this product. Default delta to 0 so we don't alert on initial load. + deltaEstoque = 0; + } + + // Save the new balance to memory + memory[idProduto] = novoSaldo; + fs.writeFileSync(memoryFile, JSON.stringify(memory, null, 2)); + + console.log(`[Stock Tracker] Product ${idProduto}: Old=${estoqueAntigo ?? 'None'} -> New=${novoSaldo}. Delta=${deltaEstoque > 0 ? '+' : ''}${deltaEstoque}`); + } + + // Inject the delta into the payload so n8n can easily read it + if (!payload.dados) payload.dados = {}; + payload.dados.delta_estoque = deltaEstoque; + await sendToN8n(payload, targetUrl); } catch (error) { console.error('Error handling Tiny stock webhook:', error);