-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
655 lines (595 loc) · 18.8 KB
/
utils.js
File metadata and controls
655 lines (595 loc) · 18.8 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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
const
crypto = require('crypto'),
request = require('request'),
mongo = require('mongoskin');
require('./constants.js')();
module.exports = function() {
this.db = mongo.db(MONGO_URI, {native_parser:true});
db.bind('companies');
db.bind('users');
db.bind('userAccounts');
/*
* Message Read Event
*
* This event is called when a previously-sent message has been read.
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-read
*
*/
this.receivedMessageRead = function (event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
// All messages before watermark (a timestamp) or sequence have been seen.
var watermark = event.read.watermark;
var sequenceNumber = event.read.seq;
console.log("Received message read event for watermark %d and sequence " +
"number %d", watermark, sequenceNumber);
};
this.linkUserAccount = function(params) {
const senderID = params['senderID'];
const authCode = params['authCode'];
const status = params['status'];
const fbDetails = params['fbDetails'];
db.users.update({"service.authCode" : authCode }, {'$set':{"fbUserId": senderID, "service.status": status, "fbInfo": fbDetails['fbInfo']}}, function(err, result) {
if (err) throw err;
if (result && result.result.nModified > 0) {
console.log(result.result.nModified);
console.log('Linked user!');
console.log("Received account link event with for user %d with status %s " +
"and auth code %s ", senderID, status, authCode);
db.users.findOne({"fbUserId" : senderID }, function(err, user) {
if (err)
throw err;
console.log(user);
if (user) {
db.userAccounts.findOne({"$and": [{"email": user.email}, {"fbUserId": senderID}]}, function(err, userAccount) {
if (err)
throw err;
console.log(userAccount);
if (userAccount) {
var text = "Welcome back " + user.name.firstName + "!\n" + "Your credit balance is " + prettifyNumber(roundup(userAccount.credit, 2)) + ".";
sendTextMessage(senderID, text);
} else {
db.userAccounts.update({"email": user.email}, {"$set": {"fbUserId": senderID}}, function(err, userAccountUpdate) {
if (err) {
throw err;
}
console.log("Finishing user registration.");
console.log(userAccountUpdate);
if (userAccountUpdate.result.nModified > 0) {
db.userAccounts.findOne({"fbUserId": senderID}, function(err, entry) {
var text = "Welcome " + user.name.firstName + "!\n" + "Your credit balance is " + prettifyNumber(roundup(entry.credit, 2)) + ".";
sendTextMessage(senderID, text);
var newpayload = {
state: "USER_SETUP",
done: false,
part: 0,
value: 0,
divisorValue: 0
};
db.users.update({"fbUserId": senderID}, {"$set": {"payload": newpayload}}, function(err, result) {
if (err)
throw err;
sendNewUserOptions(senderID);
});
});
} else {
console.log("Failed to update userAccount");
}
});
}
});
}
});
} else {
console.log('user not found - status not linked');
}
});
};
/*
* Account Link Event
*
* This event is called when the Link Account or UnLink Account action has been
* tapped.
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/account-linking
*
*/
this.receivedAccountLink = function (event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var status = event.account_linking.status;
var authCode = event.account_linking.authorization_code;
if (status == "linked") {
db.users.findOne({"fbUserId": senderID}, function(err, user) {
if (err)
throw err;
if (user && user.newUser) {
console.log("Registering new user");
var fbDetails = {};
fbDetails['fbUserId'] = user.fbUserId;
fbDetails['fbInfo'] = user.fbInfo;
db.users.remove({"fbUserId": senderID}, function(err, result) {
if (err)
throw err;
if (result) {
console.log("Deleted pre-user data");
var params = {
senderID: senderID,
status: status,
authCode: authCode,
fbDetails: fbDetails
};
linkUserAccount(params);
}
});
} else if (user) {
console.log("Logging in existing user");
var fbDetails = {};
fbDetails['fbUserId'] = user.fbUserId;
fbDetails['fbInfo'] = user.fbInfo;
var params = {
senderID: senderID,
status: status,
authCode: authCode,
fbDetails: fbDetails
};
linkUserAccount(params);
}
});
} else if (status == "unlinked") {
db.users.update({ "fbUserId" : senderID }, {'$set':{ "service.status": status} }, function(err, result) {
if (err) throw err;
if (result.result.nModified > 0) {
console.log('Unlinked user!');
console.log("Received account link event with for user %d with status %s " +
"and auth code %s ", senderID, status, authCode);
} else {
console.log('user not found - failed to set status to unlinked');
}
});
}
};
/*
* Send a button message using the Send API.
*
*/
this.sendNewUserOptions = function (recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "Welcome to Peso, your stocks assistant bot!",
buttons:[{
type: "postback",
title: "Setup account",
payload: JSON.stringify({ state: "USER_SETUP", done: false, part: 0, value: 0, divisorValue: 0})
}]
}
}
}
};
callSendAPI(messageData);
};
/*
* Send a text message using the Send API.
*
*/
this.sendTextMessage = function (recipientId, messageText, callback) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText,
metadata: "DEVELOPER_DEFINED_METADATA"
}
};
var done = false;
while (!done) {
if (isSendAPIReady) {
callSendAPI(messageData);
done = true;
}
}
callback && callback();
}
/*
* Send a message with Quick Reply buttons.
*
*/
this.sendQuickReply = function (recipientId, text, quickReplies) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: text,
quick_replies: quickReplies
}
};
var done = false;
while (!done) {
if (isSendAPIReady) {
callSendAPI(messageData);
done = true;
}
}
}
/*
* Send a message with the account linking call-to-action
*
*/
this.sendGetStarted = function (recipientId, text) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: text,
buttons:[{
type: "account_link",
url: SERVER_URL + "/authorize"
}]
}
}
}
};
var done = false;
while (!done) {
if (isSendAPIReady) {
callSendAPI(messageData);
done = true;
}
}
};
/*
* Send a message with the account linking call-to-action
*
*/
this.sendAccountLinking = function (recipientId, text) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: text,
buttons:[{
type: "account_link",
url: SERVER_URL + "/authorize"
}]
}
}
}
};
var done = false;
while (!done) {
if (isSendAPIReady) {
callSendAPI(messageData);
done = true;
}
}
};
this.sendAccountUnlinking = function (recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "Click button to unlink your account.",
buttons:[{
type: "account_unlink"
}]
}
}
}
};
var done = false;
while (!done) {
if (isSendAPIReady) {
callSendAPI(messageData);
done = true;
}
}
}
this.getUserInfo = function (userId, callback) {
request({
uri: 'https://graph.facebook.com/v2.6/'+ userId +'/',
qs: { fields: "first_name,last_name,profile_pic,locale,timezone,gender",
access_token: PAGE_ACCESS_TOKEN },
method: 'GET'
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
// var recipientId = body.recipient_id;
// var messageId = body.message_id;
console.log("Got user info: ");
console.log(body);
callback && callback(null, JSON.parse(body));
} else if (response && body) {
console.error("Failed calling Get user info API", response.statusCode, response.statusMessage, body.error);
callback && callback(new Error("Failed to get user info."), null);
} else {
console.error("Failed calling Get user info API: Unknown error occured");
callback && callback(new Error("unknown error occured."), null);
}
});
}
/*
* Call the Send API. The message data goes in the body. If successful, we'll
* get the message id in a response
*
*/
var messageQueue = [];
this.callSendAPI = function callSendAPI(messageData) {
messageQueue.push(messageData);
while(messageQueue.length != 0) {
var data = messageQueue.shift();
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else if (response && body) {
console.error("Failed sending API", response.statusCode, response.statusMessage, body.error);
} else {
console.error("Failed sending API: Unknown error occured");
}
});
}
};
this.isSendAPIReady = function() {
if (messageQueue.length == 0) {
return true;
} else {
return false;
}
}
/*
* Verify that the callback came from Facebook. Using the App Secret from
* the App Dashboard, we can verify the signature that is sent with each
* callback in the x-hub-signature field, located in the header.
*
* https://developers.facebook.com/docs/graph-api/webhooks#setup
*
*/
this.verifyRequestSignature = function (req, res, buf) {
var signature = req.headers["x-hub-signature"];
if (!signature) {
// For testing, let's log an error. In production, you should throw an
// error.
console.error("Couldn't validate the signature.");
} else {
var elements = signature.split('=');
var method = elements[0];
var signatureHash = elements[1];
var expectedHash = crypto.createHmac('sha1', APP_SECRET)
.update(buf)
.digest('hex');
if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
};
this.randomPrice = function (price, lastModified) {
var time_now = new Date();
if (marketIsOpen(time_now)) {
var tick_size = getTickSize(price);
var decimalPlaces = getDecimalPlaces(tick_size);
console.log("decimal places are " + decimalPlaces);
time_now = time_now.getTime()/1000;
lastModified = lastModified.getTime()/1000;
var time_diff_secs = Math.abs(time_now - lastModified);
var rand_range = Math.log(time_diff_secs)/2;
var direction = Math.random() < 0.5 ? -1 : 1;
console.log("Power is " + Math.pow(10, decimalPlaces));
var price_change = (Math.random() * rand_range)/100;
price_change = Math.floor((price_change * price) / tick_size);
price_change = Math.floor((price_change * tick_size * direction)*Math.pow(10, decimalPlaces))/Math.pow(10, decimalPlaces);
console.log(price_change);
var new_price = Math.floor((price_change + price) * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
return new_price;
} else {
return price;
}
};
this.getDecimalPlaces = function(value) {
var decimalPlaces = value.toString().split(".");
if (decimalPlaces.length == 2) {
decimalPlaces = decimalPlaces[1].length;
} else {
decimalPlaces = 0;
}
return decimalPlaces;
};
this.removeExtraDecimals = function (price, tick_size) {
var decimalPlaces = getDecimalPlaces(tick_size);
price = roundup(price, decimalPlaces);
return price;
}
this.roundup = function (value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
this.marketIsOpen = function (datetime) {
const hours = datetime.getHours();
const minutes = datetime. getMinutes();
if ((hours == 9 && minutes >= 30) || (hours > 9 && hours < 12)) {
return true;
} else if(hours == 13 && minutes > 30) {
return true;
} else if ((hours > 13 && hours < 15 ) || (hours == 15 && minutes < 30)) {
return true;
} else {
return false;
}
};
this.getTickSize = function(price) {
if (price <= 0.0099) {
return 0.0001;
} else if (price <= 0.0490) {
return 0.001;
} else if (price <= 0.2490) {
return 0.001;
} else if (price <= 0.4950) {
return 0.005;
} else if (price <= 4.9900) {
return 0.01;
} else if (price <= 9.9900) {
return 0.01;
} else if (price <= 19.9800) {
return 0.02;
} else if (price <= 49.9500) {
return 0.05;
} else if (price <= 99.9500) {
return 0.05;
} else if (price <= 199.9000) {
return 0.1;
} else if (price <= 499.8000) {
return 0.2;
} else if (price <= 999.5000) {
return 0.5;
} else if (price <= 1999.0000) {
return 1;
} else if (price <= 4998.0000) {
return 2;
} else if (price >= 5000.0000) {
return 5;
}
};
this.getLotSize = function(price) {
if (price <= 0.0099) {
return 1000000;
} else if (price <= 0.0490) {
return 100000;
} else if (price <= 0.2490) {
return 10000;
} else if (price <= 0.4950) {
return 10000;
} else if (price <= 4.9900) {
return 1000;
} else if (price <= 9.9900) {
return 100;
} else if (price <= 19.9800) {
return 100;
} else if (price <= 49.9500) {
return 100;
} else if (price <= 99.9500) {
return 10;
} else if (price <= 199.9000) {
return 10;
} else if (price <= 499.8000) {
return 10;
} else if (price <= 999.5000) {
return 10;
} else if (price <= 1999.0000) {
return 5;
} else if (price <= 4998.0000) {
return 5;
} else if (price >= 5000.0000) {
return 5;
}
};
this.getFees = function (state, price, shares) {
if (!state && !price && !shares) {
return null
}
const sub_total = price * shares;
const commission = sub_total * 0.0025;
const vat = commission * 0.12;
const pseTransFee = sub_total * 0.00005;
const sccp = sub_total * 0.0001;
var salesTax = 0;
if (state == "SELLING_STOCKS") {
salesTax = sub_total * 0.005;
}
const total_fees = roundup(commission + vat + pseTransFee + sccp + salesTax, 2);
console.log(total_fees);
return total_fees;
};
this.formatPriceValue = function(value) {
if (!isNaN(value)) {
return removeExtraDecimals(value, getTickSize(value));
}
return value;
};
/*
* given a number, returns a comma added string representation
* of the number
*/
this.prettifyNumber = function (x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
this.isValidPrice = function (price, symbol, callback) {
if (!isNaN(price)) {
db.companies.findOne({"symbol": symbol}, function(err, company) {
if (err)
callback && callback(err, null);
if (company) {
var tick_size = getTickSize(company.currentPrice);
var decimalPlaces = getDecimalPlaces(tick_size);
const regulator = Math.pow(10, decimalPlaces);
var remainder = (regulator * price) % (regulator* tick_size);
if (remainder == 0 && price > 0) {
callback && callback(null, true);
} else {
callback && callback(null, false);
}
} else {
console.log("company %s not found", symbol);
callback && callback(new Error("company not found", null));
}
});
} else {
callback && callback(new Error("Not a number"), null);
}
};
this.isValidAmount = function (amount, symbol, callback) {
if (!isNaN(amount)) {
db.companies.findOne({"symbol": symbol}, function(err, company) {
if (err)
callback && callback(err, null);
if (company) {
var lot_size = getLotSize(company.currentPrice);
const remainder = amount % lot_size;
if (remainder == 0 && amount > 0) {
callback && callback(null, true);
} else {
callback && callback(null, false);
}
} else {
console.log("company %s not found", symbol);
callback && callback(new Error("company not found", null));
}
});
} else {
callback && callback(new Error("Not a number"), null);
}
};
}