import NodeCache from 'node-cache'; // AI Analytics Cache with TTL (Time To Live) class AICache { constructor() { this.cache = new NodeCache({ stdTTL: 300, // 5 minutes default TTL checkperiod: 60, // Check for expired keys every 60 seconds useClones: false // Performance optimization - don't clone objects }); // Different TTL for different data types this.ttlConfig = { sales: 300, // 5 minutes - sales data changes frequently inventory: 600, // 10 minutes - inventory changes less frequently suppliers: 1800, // 30 minutes - supplier data changes rarely services: 1800, // 30 minutes - service data changes rarely predictions: 900 // 15 minutes - predictions need regular updates }; } // Generate cache key generateKey(type, tenantId, branchId, params = {}) { const paramStr = Object.keys(params) .sort() .map(key => `${key}:${params[key]}`) .join('|'); return `ai:${type}:${tenantId}:${branchId || 'all'}${paramStr ? `:${paramStr}` : ''}`; } // Get cached data get(type, tenantId, branchId, params = {}) { const key = this.generateKey(type, tenantId, branchId, params); return this.cache.get(key); } // Set cached data with appropriate TTL set(type, tenantId, branchId, data, params = {}) { const key = this.generateKey(type, tenantId, branchId, params); const ttl = this.ttlConfig[type] || 300; return this.cache.set(key, data, ttl); } // Delete cached data del(type, tenantId, branchId, params = {}) { const key = this.generateKey(type, tenantId, branchId, params); return this.cache.del(key); } // Clear all cache for a specific tenant clearTenant(tenantId) { const keys = this.cache.keys().filter(key => key.includes(`:${tenantId}:`)); return this.cache.del(keys); } // Clear cache for specific data type clearType(type) { const keys = this.cache.keys().filter(key => key.startsWith(`ai:${type}:`)); return this.cache.del(keys); } // Get cache statistics getStats() { return this.cache.getStats(); } // Pre-warm cache with common queries async warmCache(tenantId, branchId, dataFetchers) { const promises = []; // Warm sales cache for common periods [7, 30, 90].forEach(period => { promises.push( this.getOrSet('sales', tenantId, branchId, { period }, () => dataFetchers.fetchSales(period)) ); }); // Warm other caches promises.push( this.getOrSet('inventory', tenantId, branchId, {}, () => dataFetchers.fetchInventory()), this.getOrSet('suppliers', tenantId, branchId, {}, () => dataFetchers.fetchSuppliers()), this.getOrSet('services', tenantId, branchId, {}, () => dataFetchers.fetchServices()) ); try { await Promise.allSettled(promises); } catch (error) { console.warn('Cache warming failed:', error); } } // Get from cache or set if not exists async getOrSet(type, tenantId, branchId, params, fetchFunction) { const cached = this.get(type, tenantId, branchId, params); if (cached !== undefined) { return cached; } try { const data = await fetchFunction(); this.set(type, tenantId, branchId, data, params); return data; } catch (error) { console.error(`Failed to fetch ${type} data:`, error); throw error; } } } export default new AICache();