feat: add local memory tracker to calculate stock deltas
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m41s
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m41s
This commit is contained in:
@@ -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<void> => {
|
||||
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<string, number> = {};
|
||||
|
||||
// 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);
|
||||
|
||||
Reference in New Issue
Block a user