forked from parse-community/parse-server-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStats.js
More file actions
548 lines (474 loc) · 16.1 KB
/
Stats.js
File metadata and controls
548 lines (474 loc) · 16.1 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
var dateUtil = require('./DateUtil.js');
var Totals = require('./Totals.js');
var CommunityTotals = require('./CommunityTotals.js');
function Interval(start, end) {
this.start = start;
this.end = end;
this.contains = function(date) {
if (this.start <= date && this.end > date) {
return true;
} else {
return false;
}
}
}
//http://stackoverflow.com/questions/563406/add-days-to-datetime
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
}
Date.prototype.addMonths = function(months) {
var dat = new Date(this.valueOf());
dat.setMonth(dat.getMonth() + months);
return dat;
}
/*
Adds contents of 2 arrays, arrays must be same length and contain numbers
*/
function addArrayContents(one, two) {
if (one && two && one.length == two.length) {
return one.map(function(e, i) {
return e + two[i];
});
}
return one;
}
/*
Sums the contents of an array
*/
function sumArray(arr) {
if (!arr) {
return 0;
}
return arr.reduce(function(a, b) {
return a + b;
});
}
Parse.Cloud.define("stats", function(request, response) {
Parse.Cloud.useMasterKey();
//number of queries that need to complete successfully to return success
var queryCount = 4;
var failureFlag = false;
var responseObj = {};
//setup daily intervals
var startDate = new Date();
startDate.setHours(0, 0, 0, 0); //midnight today
var endDate = new Date(startDate);
endDate = endDate.addDays(1); //midnight tomorrow
var dayIntervals = [];
for (var i = 0; i < 7; i++) {
dayIntervals.push(new Interval(startDate, endDate));
startDate = startDate.addDays(-1);
endDate = endDate.addDays(-1);
}
//setup monthly intervals
startDate = new Date();
startDate.setHours(0, 0, 0, 0); //midnight today
startDate.setDate(1); //midnight, first day of the month
endDate = new Date(startDate);
endDate.setMonth(endDate.getMonth() + 1); //midnight, first day of next month
var monthIntervals = [];
for (var i = 0; i < 12; i++) {
monthIntervals.push(new Interval(new Date(startDate), new Date(endDate)));
startDate.setMonth(startDate.getMonth() - 1);
endDate.setMonth(endDate.getMonth() - 1);
}
//stats for friends
var user = new Parse.User({
id: request.params.userId
});
var userQuery = new Parse.Query("POFriendRelation");
userQuery.equalTo("userId", user);
userQuery.find({
success: function(friendRelations) {
if (friendRelations && friendRelations.length > 0) {
var friends = friendRelations.map(function(e) {
return e.get("friendUser");
});
var userTotalsQuery = new Parse.Query("UserTotals");
userTotalsQuery.containedIn("user", friends);
userTotalsQuery.find({
success: function(userTotals) {
responseObj.friends = friendsStatsFromUserTotals(userTotals, dayIntervals, monthIntervals);
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving monthly totals");
}
});
} else {
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error looking up friends");
}
});
//global stats
responseObj.global = {};
var monthlyQuery = new Parse.Query("MonthlyTotals");
monthlyQuery.lessThan("date",new Date());
monthlyQuery.addDescending("date");
monthlyQuery.limit(monthIntervals.length); //last 12 months of data
monthlyQuery.find({
success: function(monthlyResults) {
responseObj.global.minutesDrivenMonths = [];
responseObj.global.kmDrivenMonths = [];
for (var i = 0; i < monthIntervals.length; i++) {
if (i < monthlyResults.length) {
var object = monthlyResults[i];
responseObj.global.minutesDrivenMonths.push({
date: object.get("date"),
count: object.get("minutesTravelled")
});
responseObj.global.kmDrivenMonths.push({
date: object.get("date"),
count: (object.get("distanceTravelled") / 1000)
});
} else {
responseObj.global.minutesDrivenMonths.push({
date: monthIntervals[i].start,
count: 0
});
responseObj.global.kmDrivenMonths.push({
date: monthIntervals[i].start,
count: 0
});
}
}
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving monthly totals");
}
});
var dailyQuery = new Parse.Query("DailyTotals");
dailyQuery.lessThan("date",new Date());
dailyQuery.addDescending("date");
dailyQuery.limit(dayIntervals.length); //last 7 days of data
dailyQuery.find({
success: function(dailyResults) {
responseObj.global.minutesDrivenDays = [];
responseObj.global.kmDrivenDays = [];
for (var i = 0; i < dayIntervals.length; i++) {
if (i < dailyResults.length) {
var object = dailyResults[i];
responseObj.global.minutesDrivenDays.push({
date: object.get("date"),
count: object.get("minutesTravelled")
});
responseObj.global.kmDrivenDays.push({
date: object.get("date"),
count: (object.get("distanceTravelled") / 1000)
});
} else {
responseObj.global.minutesDrivenDays.push({
date: dayIntervals[i].start,
count: 0
});
responseObj.global.kmDrivenDays.push({
date: dayIntervals[i].start,
count: 0
});
}
}
var mostRecent = dailyResults[0];
if (mostRecent) {
responseObj.global.total_users_daily_increase = mostRecent.get("users");
}
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving daily totals");
}
});
var globalQuery = new Parse.Query("GlobalTotals");
globalQuery.first({
success: function(results) {
responseObj.global.missedMessages = results.get("missedSMSCount");
responseObj.global.missedCalls = results.get("missedCallCount");
responseObj.global.missedNotifications = results.get("missedOtherCount");
responseObj.global.total_users = results.get("users");
responseObj.global.totalTrips = results.get("trips");
responseObj.global.totalDistance = results.get("distanceTravelled");
responseObj.global.totalDuration = results.get("minutesTravelled") * 60;
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving global totals");
}
});
});
function friendsStatsFromUserTotals(userTotals, dayIntervals, monthIntervals) {
friends = {};
friends.missedMessages = 0;
friends.missedCalls = 0;
friends.missedNotifications = 0;
friends.totalDistance = 0;
friends.totalDuration = 0;
friends.totalTrips = 0;
var kmDrivenDays = [0,0,0,0,0,0,0];
var minutesDrivenDays = [0,0,0,0,0,0,0];
friends.leaderboardDays = {};
var kmDrivenMonths = [0,0,0,0,0,0,0,0,0,0,0,0];
var minutesDrivenMonths = [0,0,0,0,0,0,0,0,0,0,0,0];
friends.leaderboardMonths = {};
if (userTotals) {
for (var i = 0; i < userTotals.length; i++) {
Totals.pushArraysIfnecessary(userTotals[i]);//make sure arrays are set for current day
friends.missedMessages += userTotals[i].get("missedSMSCount") ? userTotals[i].get("missedSMSCount") : 0;
friends.missedCalls += userTotals[i].get("missedCallCount") ? userTotals[i].get("missedCallCount") : 0;
friends.missedNotifications += userTotals[i].get("missedOtherCount") ? userTotals[i].get("missedOtherCount") : 0;
friends.totalDistance += userTotals[i].get("distanceTravelled") ? userTotals[i].get("distanceTravelled") : 0;
friends.totalDuration += userTotals[i].get("minutesTravelled") ? userTotals[i].get("minutesTravelled") : 0;
friends.totalTrips += userTotals[i].get("trips") ? userTotals[i].get("trips") : 0;
kmDrivenDays = addArrayContents(kmDrivenDays, userTotals[i].get("dayDistanceTravelled"));
minutesDrivenDays = addArrayContents(minutesDrivenDays, userTotals[i].get("dayMinutesTravelled"));
var userId = userTotals[i].get("user").id;
friends.leaderboardDays[userId] = {};
friends.leaderboardDays[userId].meters = sumArray(userTotals[i].get("dayDistanceTravelled"));
friends.leaderboardDays[userId].min = sumArray(userTotals[i].get("dayMinutesTravelled"));
kmDrivenMonths = addArrayContents(kmDrivenMonths, userTotals[i].get("monthDistanceTravelled"));
minutesDrivenMonths = addArrayContents(minutesDrivenMonths, userTotals[i].get("monthMinutesTravelled"));
friends.leaderboardMonths[userId] = {};
friends.leaderboardMonths[userId].meters = sumArray(userTotals[i].get("monthDistanceTravelled"));
friends.leaderboardMonths[userId].min = sumArray(userTotals[i].get("monthMinutesTravelled"));
}
friends.totalDuration = friends.totalDuration * 60;
}
friends.kmDrivenDays = [];
friends.minutesDrivenDays = [];
for (var i = 0; i < dayIntervals.length; i++) {
friends.kmDrivenDays[i] = {
date: dayIntervals[i].start,
count: (kmDrivenDays[i] / 1000)
};
friends.minutesDrivenDays[i] = {
date: dayIntervals[i].start,
count: minutesDrivenDays[i]
};
}
friends.kmDrivenMonths = [];
friends.minutesDrivenMonths = [];
for (var i = 0; i < monthIntervals.length; i++) {
friends.kmDrivenMonths[i] = {
date: monthIntervals[i].start,
count: (kmDrivenMonths[i] / 1000)
};
friends.minutesDrivenMonths[i] = {
date: monthIntervals[i].start,
count: minutesDrivenMonths[i]
};
}
return friends;
}
Parse.Cloud.define("communityStats", function(request, response) {
//number of queries that need to complete successfully to return success
var queryCount = 3;
var failureFlag = false;
var responseObj = {};
//setup daily intervals
var startDate = new Date();
startDate.setHours(0, 0, 0, 0); //midnight today
var endDate = new Date(startDate);
endDate = endDate.addDays(1); //midnight tomorrow
var dayIntervals = [];
for (var i = 0; i < 7; i++) {
dayIntervals.push(new Interval(startDate, endDate));
startDate = startDate.addDays(-1);
endDate = endDate.addDays(-1);
}
//setup monthly intervals
startDate = new Date();
startDate.setHours(0, 0, 0, 0); //midnight today
startDate.setDate(1); //midnight, first day of the month
endDate = new Date(startDate);
endDate.setMonth(endDate.getMonth() + 1); //midnight, first day of next month
var monthIntervals = [];
for (var i = 0; i < 12; i++) {
monthIntervals.push(new Interval(new Date(startDate), new Date(endDate)));
startDate.setMonth(startDate.getMonth() - 1);
endDate.setMonth(endDate.getMonth() - 1);
}
var community = request.user.get("community");
var monthlyQuery = new Parse.Query("CommunityMonthlyTotals");
monthlyQuery.equalTo("community", community);
monthlyQuery.lessThan("date", new Date());
monthlyQuery.addDescending("date");
monthlyQuery.limit(monthIntervals.length); //last 12 months of data
monthlyQuery.find({
success: function(monthlyResults) {
responseObj.minutesDrivenMonths = [];
responseObj.kmDrivenMonths = [];
for (var i = 0; i < monthIntervals.length; i++) {
if (i < monthlyResults.length) {
var object = monthlyResults[i];
responseObj.minutesDrivenMonths.push({
date: object.get("date"),
count: object.get("minutesTravelled")
});
responseObj.kmDrivenMonths.push({
date: object.get("date"),
count: (object.get("distanceTravelled") / 1000)
});
} else {
responseObj.minutesDrivenMonths.push({
date: monthIntervals[i].start,
count: 0
});
responseObj.kmDrivenMonths.push({
date: monthIntervals[i].start,
count: 0
});
}
}
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving monthly totals");
}
});
var dailyQuery = new Parse.Query("CommunityDailyTotals");
dailyQuery.equalTo("community", community);
dailyQuery.lessThan("date",new Date());
dailyQuery.addDescending("date");
dailyQuery.limit(dayIntervals.length); //last 7 days of data
dailyQuery.find({
success: function(dailyResults) {
responseObj.minutesDrivenDays = [];
responseObj.kmDrivenDays = [];
for (var i = 0; i < dayIntervals.length; i++) {
if (i < dailyResults.length) {
var object = dailyResults[i];
responseObj.minutesDrivenDays.push({
date: object.get("date"),
count: object.get("minutesTravelled")
});
responseObj.kmDrivenDays.push({
date: object.get("date"),
count: (object.get("distanceTravelled") / 1000)
});
} else {
responseObj.minutesDrivenDays.push({
date: dayIntervals[i].start,
count: 0
});
responseObj.kmDrivenDays.push({
date: dayIntervals[i].start,
count: 0
});
}
}
var mostRecent = dailyResults[0];
if (mostRecent) {
responseObj.total_users_daily_increase = mostRecent.get("addedUsers");
}
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving daily totals");
}
});
var allTimeQuery = new Parse.Query("CommunityAllTimeTotals");
allTimeQuery.equalTo("community", community);
allTimeQuery.first({
success: function(results) {
responseObj.missedMessages = results.get("missedSMSCount");
responseObj.missedCalls = results.get("missedCallCount");
responseObj.missedNotifications = results.get("missedOtherCount");
responseObj.total_users = results.get("addedUsers") - results.get("removedUsers");
responseObj.totalTrips = results.get("trips");
responseObj.totalDistance = results.get("distanceTravelled");
responseObj.totalDuration = results.get("minutesTravelled") * 60;
if (--queryCount == 0 && !failureFlag) {
response.success(responseObj);
}
},
error: function(error) {
failureFlag = true;
console.error("Got an error " + error.code + " : " + error.message);
response.error("Error retrieving all time totals");
}
});
});
Parse.Cloud.job("statForwardJob", function(request, status) {
// add rows for community totals and normal totals
var communityQuery = new Parse.Query("Community");
communityQuery.find({
success: function(results) {
var callCount = 2;
callCount += results.length * 3;
// Add rows for the normal totals
var currDate = new Date();
Totals.getDailyTotals(currDate.addDays(1), function(sucessObj) {
if (--callCount == 0) {
status.success("new stats rows created");
}
}, function(error) {
status.error("daily rows creation failure");
});
Totals.getMonthlyTotals(currDate.addMonths(1), function(sucessObj) {
if (--callCount == 0) {
status.success("new stats rows created");
}
}, function(error) {
status.error("monthly rows creation failure");
});
// Add rows for the community totals
for (var i = 0; i < results.length; i++) {
var community = results[i];
CommunityTotals.getAllTimeTotals(community, function(sucessObj) {
if (--callCount == 0) {
status.success("new stats rows created");
}
});
CommunityTotals.getDailyTotals(community, currDate.addDays(1), function(sucessObj) {
if (--callCount == 0) {
status.success("new stats rows created");
}
}, function(error) {
status.error("daily rows creation failure");
});
CommunityTotals.getMonthlyTotals(community, currDate.addMonths(1), function(sucessObj) {
if (--callCount == 0) {
status.success("new stats rows created");
}
}, function(error) {
status.error("monthly rows creation failure");
});
};
},
error: function(error) {
status.error("error when loading communities to create total rows");
}
});
});