File size: 6,747 Bytes
e7427b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// User Analytics and Tracking System for प्रिथ्वी Guardian AI
interface UserSession {
  sessionId: string;
  startTime: Date;
  endTime?: Date;
  pageViews: string[];
  actionsPerformed: string[];
  modulesUsed: string[];
  calculationsCount: number;
  reportsGenerated: number;
  timeSpent: number; // in minutes
}

interface UserAnalytics {
  totalSessions: number;
  totalUsers: number;
  averageSessionTime: number;
  mostUsedModules: Record<string, number>;
  dailyActiveUsers: Record<string, number>;
  featureUsage: Record<string, number>;
  retentionRate: number;
}

class UserTrackingSystem {
  private currentSession: UserSession | null = null;
  private sessionKey = 'prithvi_user_session';
  private analyticsKey = 'prithvi_analytics';
  private userIdKey = 'prithvi_user_id';

  constructor() {
    this.initializeTracking();
  }

  private initializeTracking() {
    // Generate unique user ID if not exists
    if (!localStorage.getItem(this.userIdKey)) {
      const userId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
      localStorage.setItem(this.userIdKey, userId);
    }

    // Start new session
    this.startSession();

    // Track page visibility changes
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        this.pauseSession();
      } else {
        this.resumeSession();
      }
    });

    // Track before page unload
    window.addEventListener('beforeunload', () => {
      this.endSession();
    });
  }

  startSession() {
    const sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    this.currentSession = {
      sessionId,
      startTime: new Date(),
      pageViews: [window.location.pathname],
      actionsPerformed: [],
      modulesUsed: [],
      calculationsCount: 0,
      reportsGenerated: 0,
      timeSpent: 0
    };

    localStorage.setItem(this.sessionKey, JSON.stringify(this.currentSession));
    this.updateAnalytics('sessionStart');
  }

  trackPageView(path: string) {
    if (!this.currentSession) return;
    
    this.currentSession.pageViews.push(path);
    this.updateSession();
    this.updateAnalytics('pageView', { path });
  }

  trackAction(action: string, details?: any) {
    if (!this.currentSession) return;
    
    const actionLog = {
      action,
      timestamp: new Date(),
      details
    };
    
    this.currentSession.actionsPerformed.push(JSON.stringify(actionLog));
    this.updateSession();
    this.updateAnalytics('action', { action });
  }

  trackModuleUsage(module: string) {
    if (!this.currentSession) return;
    
    if (!this.currentSession.modulesUsed.includes(module)) {
      this.currentSession.modulesUsed.push(module);
    }
    this.updateSession();
    this.updateAnalytics('moduleUsage', { module });
  }

  trackCalculation(module: string, type: string) {
    if (!this.currentSession) return;
    
    this.currentSession.calculationsCount++;
    this.trackAction('calculation', { module, type });
    this.trackModuleUsage(module);
    this.updateSession();
  }

  trackReportGeneration(title: string) {
    if (!this.currentSession) return;
    
    this.currentSession.reportsGenerated++;
    this.trackAction('reportGenerated', { title });
    this.updateSession();
  }

  private updateSession() {
    if (!this.currentSession) return;
    
    const now = new Date();
    this.currentSession.timeSpent = Math.round((now.getTime() - this.currentSession.startTime.getTime()) / 60000);
    localStorage.setItem(this.sessionKey, JSON.stringify(this.currentSession));
  }

  private pauseSession() {
    this.updateSession();
  }

  private resumeSession() {
    // Session continues, just update time
    this.updateSession();
  }

  endSession() {
    if (!this.currentSession) return;
    
    this.currentSession.endTime = new Date();
    this.updateSession();
    
    // Save to permanent storage
    this.saveSessionToHistory();
    this.updateAnalytics('sessionEnd');
    
    this.currentSession = null;
    localStorage.removeItem(this.sessionKey);
  }

  private saveSessionToHistory() {
    if (!this.currentSession) return;
    
    const historyKey = 'prithvi_session_history';
    const history = JSON.parse(localStorage.getItem(historyKey) || '[]');
    history.push(this.currentSession);
    
    // Keep only last 100 sessions
    if (history.length > 100) {
      history.splice(0, history.length - 100);
    }
    
    localStorage.setItem(historyKey, JSON.stringify(history));
  }

  private updateAnalytics(eventType: string, data?: any) {
    const analytics = this.getAnalytics();
    const today = new Date().toISOString().split('T')[0];
    
    switch (eventType) {
      case 'sessionStart':
        analytics.totalSessions++;
        analytics.dailyActiveUsers[today] = (analytics.dailyActiveUsers[today] || 0) + 1;
        break;
      case 'moduleUsage':
        analytics.mostUsedModules[data.module] = (analytics.mostUsedModules[data.module] || 0) + 1;
        break;
      case 'action':
        analytics.featureUsage[data.action] = (analytics.featureUsage[data.action] || 0) + 1;
        break;
    }
    
    localStorage.setItem(this.analyticsKey, JSON.stringify(analytics));
  }

  getAnalytics(): UserAnalytics {
    const defaultAnalytics: UserAnalytics = {
      totalSessions: 0,
      totalUsers: 1,
      averageSessionTime: 0,
      mostUsedModules: {},
      dailyActiveUsers: {},
      featureUsage: {},
      retentionRate: 100
    };
    
    const stored = localStorage.getItem(this.analyticsKey);
    return stored ? { ...defaultAnalytics, ...JSON.parse(stored) } : defaultAnalytics;
  }

  getCurrentSession(): UserSession | null {
    return this.currentSession;
  }

  getSessionHistory(): UserSession[] {
    const historyKey = 'prithvi_session_history';
    return JSON.parse(localStorage.getItem(historyKey) || '[]');
  }

  getUserId(): string {
    return localStorage.getItem(this.userIdKey) || 'anonymous';
  }

  exportAnalyticsData(): string {
    const data = {
      userId: this.getUserId(),
      analytics: this.getAnalytics(),
      sessionHistory: this.getSessionHistory(),
      currentSession: this.currentSession,
      exportDate: new Date().toISOString()
    };
    
    return JSON.stringify(data, null, 2);
  }

  clearAnalyticsData() {
    localStorage.removeItem(this.analyticsKey);
    localStorage.removeItem('prithvi_session_history');
    localStorage.removeItem(this.sessionKey);
    // Don't clear user ID to maintain identity
  }
}

// Create global instance
export const userTracking = new UserTrackingSystem();

// Export for use in components
export { UserTrackingSystem };
export type { UserSession, UserAnalytics };