-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
236 lines (206 loc) · 7.22 KB
/
app.js
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
// Import necessary modules
const express = require('express');
const http = require('http');
const url = require('url');
const request = require('request');
const passport = require('passport');
const session = require('express-session');
require('dotenv').config();
// Create Express app
const app = express();
app.use(session({
secret: process.env.EXPRESS_SESSION_SECRET
}));
// Initialise Passport and define serialization
// TODO: Implement database storage/access
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user)
});
passport.deserializeUser(function(user, done) {
done(null, user)
});
// Set viewing engine to Jade
app.set("view engine", "jade");
// Allow serving of static files from the 'public' directory
app.use(express.static('public'));
// Serve Hello World as project root
app.get('/', (req, res) => res.render('index'));
// Sends an HTTP request to the specified endpoint for the Monzo API
// and returns a promise
function fetchMonzoData(endpoint, account_id, accessToken) {
return new Promise(function(resolve, reject) {
request({
url: 'https://api.monzo.com/' + endpoint,
qs: {'account_id': account_id},
auth: {'bearer': accessToken}
}, function(err, resp, body) {
console.log(body);
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
// Serve logged-in dash page
app.get('/dash', function(req, res) {
// Parse the raw user profile and retrieve the accounts field
const user = req.session.user;
const accs = JSON.parse(req.session.user.profile._raw).accounts;
const currentAccount = accs[1];
console.log("ACCOUNT INFO");
console.log(accs);
// Create a promise for a Monzo balance request
let balance;
let balancePromise = fetchMonzoData('balance', currentAccount.id, user.accessToken);
// Promise handling for Monzo data
balancePromise.then(JSON.parse, () => console.log("Balance Error"))
.then(function(result) {
// Succesfully fetched a Monzo balance
balance = result;
// Return a promise for the list of transactions
return fetchMonzoData('transactions', currentAccount.id, user.accessToken);
})
.then(function(data) {
// Logging for debug purposes
logData(data);
// We now have access to both the balance and the transactions list.
// Parse the raw JSON to allow extraction of transactions.
let transactions = JSON.parse(data).transactions;
const strippedTransactions = stripDeposits(transactions);
const problems = findProblems(strippedTransactions);
// Render the dashboard view with all the data it needs
res.render('dashboard', {
name: {
first: user.profile.displayName.split(' ')[0]
},
balance: toDec(balance.balance),
transactions: strippedTransactions,
maxTransaction: problems[0],
mostFrequent: problems[1]
});
});
});
const fakeTransactions = require('./transactions');
// Removes deposits and converts negative transaction amounts
// to positive integers
function stripDeposits(transactions) {
const stripped = [];
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].amount < 0) {
transactions[i].amount = "£" + toDec(transactions[i].amount * -1);
stripped.push(transactions[i]);
}
}
return fakeTransactions;
}
// Converts an integer to a 2 decimal digit string
// (e.g. 354 -> 3.54)
function toDec(amount) {
return (amount / 100).toFixed(2);
}
// Finds problematic transactions
function findProblems(transactions) {
let maxTransaction = findMax(transactions);
let mostFrequent = findMostFrequent(transactions);
return [maxTransaction, mostFrequent];
}
// Returns the largest transaction in a list
function findMax(transactions) {
let maxTransaction = {};
let maxAmount = 0;
for (let i = 0; i < transactions.length; i++) {
let entry = transactions[i];
let amount = parseFloat(entry.amount.replace("£", ""));
if (amount > maxAmount) {
maxAmount = amount;
maxTransaction = entry;
}
}
console.log(maxTransaction);
return maxTransaction;
}
// Returns a pseudo-transaction containing the most frequently
// visited merchant and the total amount spent there
function findMostFrequent(transactions) {
var merchants = {};
for (let i = 0; i < transactions.length; i++) {
let entry = transactions[i];
if (!merchants[entry.merchant]) {
merchants[entry.merchant] = [0, 0];
}
merchants[entry.merchant][0] += 1;
merchants[entry.merchant][1] += getValue(entry.amount);
}
let maxMerchant = "";
let maxVisitCount = 0;
let amountSpent = 0;
for (let merchant in merchants) {
let merchantInfo = merchants[merchant];
if (merchantInfo[0] > maxVisitCount) {
maxMerchant = merchant;
maxVisitCount = merchantInfo[0];
amountSpent = merchantInfo[1];
}
}
return {
merchant: maxMerchant,
visits: maxVisitCount,
amount: amountSpent
}
}
console.log(findProblems(fakeTransactions));
// Returns a float value from a string like £12.31
function getValue(value) {
return parseFloat(value.replace("£", ""));
}
// Miscellaneous logging for debug purposes
function logData(data) {
console.log("TRANSACTIONS");
console.log(data);
console.log("PARSED TRANSACTIONS");
console.log(JSON.parse(data).transactions);
}
// Configure Monzo Authentication
let MonzoStrategy = require('passport-monzo').Strategy;
passport.use(new MonzoStrategy({
clientID: process.env.MONZO_CLIENT_ID,
clientSecret: process.env.MONZO_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/monzo/callback'
},
function (accessToken, refreshToken, profile, done) {
console.log(profile);
let user = {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
};
return done(null, user);
}
));
// Endpoint for Monzo authentication
app.get('/auth/monzo', passport.authenticate('monzo'));
// Called after succesful authentication
app.get('/auth/monzo/callback',
passport.authenticate('monzo', {session: true, failureRedirect: '/login_fail'}),
function(req, res) {
console.log("AUTH SUCCESSFUL");
// console.log(req.user);
req.session.user = req.user;
res.redirect('/dash');
}
);
// Listen on Port 3000
app.listen(3000, () => console.log('Listening on Port 3000!'));
// Websocket
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send(1000);
});