File size: 3,797 Bytes
c6a4aaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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();