-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.gs
More file actions
349 lines (303 loc) · 9.82 KB
/
User.gs
File metadata and controls
349 lines (303 loc) · 9.82 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// User.gs - User management and usage tracking with PostgreSQL backend
// Initialize user in backend (called after authentication)
function initializeUserInBackend(userEmail) {
try {
var config = getConfig();
var response = makeApiRequest('/api/users/initialize', {
method: 'POST',
payload: {
email: userEmail,
addOnId: config.ADDON_ID,
addOnName: config.ADDON_NAME,
version: config.VERSION
}
});
if (response.success && response.json) {
Logger.log('User initialized in backend: ' + userEmail);
return response.json;
} else {
Logger.log('Backend user initialization failed: ' + response.body);
// Don't throw error - let user continue with local functionality
return { success: false, error: response.body };
}
} catch (error) {
Logger.log('Error initializing user in backend: ' + error.toString());
return { success: false, error: error.toString() };
}
}
// Get user usage data (syncs, subscription, etc.)
function getUserUsageData() {
try {
if (!isAuthenticated()) {
return {
success: false,
error: 'User not authenticated'
};
}
var userEmail = getUserEmail();
var config = getConfig();
// Try to get from backend first
var response = makeApiRequest('/api/users/usage', {
method: 'GET'
});
if (response.success && response.json) {
return {
success: true,
email: userEmail,
count: response.json.refreshesUsed || 0,
limit: response.json.refreshLimit || config.FREE_SYNC_LIMIT,
plan: response.json.plan || 'free',
resetDate: response.json.resetDate || getNextMonthStart(),
subscriptionStatus: response.json.subscriptionStatus || 'free'
};
} else {
// Fallback to local storage for offline functionality
Logger.log('Backend unavailable, using local storage');
return getLocalUsageData(userEmail, config);
}
} catch (error) {
Logger.log('Error getting user usage data: ' + error.toString());
// Fallback to local storage
var userEmail = getUserEmail();
var config = getConfig();
return getLocalUsageData(userEmail, config);
}
}
// Local fallback usage tracking (ES5 compatible)
function getLocalUsageData(userEmail, config) {
try {
var userProperties = PropertiesService.getUserProperties();
var currentMonth = getMonthStart();
var storedMonth = userProperties.getProperty('usage_month');
var syncCount = parseInt(userProperties.getProperty('sync_count') || '0');
// Reset count if new month
if (storedMonth !== currentMonth) {
syncCount = 0;
userProperties.setProperties({
'sync_count': '0',
'usage_month': currentMonth
});
}
return {
success: true,
email: userEmail,
count: syncCount,
limit: config.FREE_SYNC_LIMIT,
plan: 'free',
resetDate: getNextMonthStart(),
subscriptionStatus: 'free',
isLocal: true
};
} catch (error) {
Logger.log('Error with local usage data: ' + error.toString());
return {
success: false,
error: error.toString()
};
}
}
// Track sync usage (increment counter)
function trackSyncUsage() {
try {
var userEmail = getUserEmail();
var config = getConfig();
// Try to track in backend first
var response = makeApiRequest('/api/users/track-usage', {
method: 'POST',
payload: {
addOnId: config.ADDON_ID,
action: 'sync'
}
});
if (response.success) {
Logger.log('Sync usage tracked in backend for: ' + userEmail);
return response.json;
} else {
// Fallback to local tracking
Logger.log('Backend tracking failed, using local tracking');
return trackLocalSyncUsage();
}
} catch (error) {
Logger.log('Error tracking sync usage: ' + error.toString());
return trackLocalSyncUsage();
}
}
// Local sync tracking fallback
function trackLocalSyncUsage() {
try {
var userProperties = PropertiesService.getUserProperties();
var currentMonth = getMonthStart();
var storedMonth = userProperties.getProperty('usage_month');
var syncCount = parseInt(userProperties.getProperty('sync_count') || '0');
// Reset if new month
if (storedMonth !== currentMonth) {
syncCount = 0;
userProperties.setProperty('usage_month', currentMonth);
}
// Increment counter
syncCount++;
userProperties.setProperty('sync_count', syncCount.toString());
return {
success: true,
count: syncCount,
isLocal: true
};
} catch (error) {
Logger.log('Error with local sync tracking: ' + error.toString());
return {
success: false,
error: error.toString()
};
}
}
// Check if user can perform sync (has remaining quota)
function canUserSync() {
try {
var usage = getUserUsageData();
if (!usage.success) {
// If we can't get usage data, allow sync (fail open)
return { allowed: true, reason: 'Usage data unavailable' };
}
if (usage.plan !== 'free') {
// Paid users have unlimited syncs
return { allowed: true, reason: 'Premium plan' };
}
if (usage.count >= usage.limit) {
return {
allowed: false,
reason: 'Monthly limit exceeded',
count: usage.count,
limit: usage.limit,
resetDate: usage.resetDate
};
}
return {
allowed: true,
remaining: usage.limit - usage.count,
count: usage.count,
limit: usage.limit
};
} catch (error) {
Logger.log('Error checking user sync permission: ' + error.toString());
// Fail open - allow sync if we can't determine usage
return { allowed: true, reason: 'Error checking limits' };
}
}
// Get subscription status and upgrade URL
function getSubscriptionInfo() {
try {
var userEmail = getUserEmail();
var config = getConfig();
var response = makeApiRequest('/api/users/subscription', {
method: 'GET'
});
if (response.success && response.json) {
return {
success: true,
plan: response.json.plan || 'free',
status: response.json.status || 'active',
upgradeUrl: response.json.upgradeUrl || (config.API_BASE_URL.replace('api.', '') + '/upgrade'),
manageUrl: response.json.manageUrl || null,
nextBillingDate: response.json.nextBillingDate || null
};
} else {
// Fallback for free users
return {
success: true,
plan: 'free',
status: 'active',
upgradeUrl: config.API_BASE_URL.replace('api.', '') + '/upgrade'
};
}
} catch (error) {
Logger.log('Error getting subscription info: ' + error.toString());
return {
success: false,
error: error.toString()
};
}
}
// Upgrade flow initiation
function initiateUpgradeFlow() {
try {
var subscriptionInfo = getSubscriptionInfo();
if (subscriptionInfo.success && subscriptionInfo.upgradeUrl) {
var ui = SpreadsheetApp.getUi();
var response = ui.alert(
'Upgrade to dflo.io Pro',
'Upgrade to Pro for unlimited syncs across all dflo.io add-ons!\n\n' +
'• Unlimited monthly syncs\n' +
'• Access to all dflo.io connectors\n' +
'• Priority support\n' +
'• Advanced scheduling\n\n' +
'Visit: ' + subscriptionInfo.upgradeUrl + '\n\n' +
'Would you like to open the upgrade page?',
ui.ButtonSet.YES_NO
);
if (response === ui.Button.YES) {
// Note: Apps Script can't directly open URLs, but we can provide the link
var linkHtml = HtmlService.createHtmlOutput(
'<script>window.open("' + subscriptionInfo.upgradeUrl + '", "_blank"); google.script.host.close();</script>'
);
ui.showModalDialog(linkHtml, 'Opening upgrade page...');
}
}
return {
success: true,
message: 'Upgrade information displayed'
};
} catch (error) {
Logger.log('Error initiating upgrade flow: ' + error.toString());
return {
success: false,
error: error.toString()
};
}
}
// Helper function to get next month start date
function getNextMonthStart() {
var now = new Date();
var nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
return nextMonth.toISOString().split('T')[0];
}
// Clean up old local data (call periodically)
function cleanupLocalData() {
try {
var userProperties = PropertiesService.getUserProperties();
var currentMonth = getMonthStart();
var storedMonth = userProperties.getProperty('usage_month');
// If it's a new month, reset counters
if (storedMonth && storedMonth !== currentMonth) {
userProperties.setProperty('sync_count', '0');
userProperties.setProperty('usage_month', currentMonth);
Logger.log('Local usage data reset for new month');
}
return { success: true };
} catch (error) {
Logger.log('Error cleaning up local data: ' + error.toString());
return { success: false, error: error.toString() };
}
}
// Sync user data with backend (call after successful operations)
function syncUserDataWithBackend(operationType, metadata) {
try {
var userEmail = getUserEmail();
var config = getConfig();
var payload = {
email: userEmail,
addOnId: config.ADDON_ID,
operationType: operationType || 'sync',
timestamp: new Date().toISOString(),
metadata: metadata || {}
};
// Make async call to backend (fire and forget)
makeApiRequest('/api/users/sync-data', {
method: 'POST',
payload: payload
});
// Don't wait for response or handle errors - this is just for analytics
} catch (error) {
// Silently fail - sync is not critical
Logger.log('Background sync failed: ' + error.toString());
}
}