-
Notifications
You must be signed in to change notification settings - Fork 0
/
GlobalContext.js
778 lines (650 loc) · 20.1 KB
/
GlobalContext.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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
import React from "react";
import _ from "lodash";
import moment from "moment";
import { Notifications } from "expo";
import * as Permissions from "expo-permissions";
import hoistNonReactStatic from "hoist-non-react-statics";
import defaultTransactions from "./data/transactions.json";
import defaultCategories from "./data/categories.json";
import {
createNewTransaction,
calculateHashForPlaidTransaction,
handleDuplicateHashTransactionsFromPlaid
} from "./utils/TransactionUtils";
import {
saveItem,
loadItem,
removeItem,
clearStorage
} from "./utils/StorageUtils";
import { dbRemoveInstitutionAccount } from "./utils/DataBaseCommunication";
import * as firebase from "firebase/app";
import "firebase/auth";
import "firebase/functions";
import "firebase/firestore";
import * as Amplitude from "expo-analytics-amplitude";
import * as Sentry from "sentry-expo";
export const GlobalContext = React.createContext({});
import {
FIREBASE_API_KEY,
FIREBASE_AUTH_DOMAIN,
FIREBASE_DATABASE_URL,
FIREBASE_PROJECT_ID,
FIREBASE_STORAGE_BUCKET,
FIREBASE_MESSAGING_SENDER_ID,
FIREBASE_APP_ID,
FIREBASE_MEASUREMENT_ID,
AMPLITUDE_API_KEY
} from "react-native-dotenv";
const ENVIRONMENT = "production"; // or "sandbox"
export class GlobalContextProvider extends React.Component {
cleanState = {
transactions: [],
categories: [],
notificationTime: {
hours: 8,
minutes: 0
},
institutionAccounts: []
};
state = this.cleanState;
constructor() {
super();
var firebaseConfig = {
apiKey: FIREBASE_API_KEY,
authDomain: FIREBASE_AUTH_DOMAIN,
databaseURL: FIREBASE_DATABASE_URL,
projectId: FIREBASE_PROJECT_ID,
storageBucket: FIREBASE_STORAGE_BUCKET,
messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
appId: FIREBASE_APP_ID
};
firebase.initializeApp(firebaseConfig);
firebase.functions();
Amplitude.initialize(AMPLITUDE_API_KEY);
}
loadStateFromStorage = async () => {
if (await this.isUserLoggedIn()) {
const uid = (await this.getCurrentUser()).uid;
Amplitude.setUserId(uid);
try {
const transactions = await loadItem(uid, "transactions");
this.setTransactions(transactions, false);
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
try {
const savedCategories = await loadItem(uid, "categories");
// if savedCategories is null, then use default categories
const categories = savedCategories
? savedCategories
: defaultCategories;
this.setState({ categories });
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
try {
let notificationTime = await loadItem(uid, "notificationTime");
if (!notificationTime) {
notificationTime = this.state.notificationTime;
}
this.setState({ notificationTime });
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
try {
let institutionAccounts = await loadItem(uid, "institutionAccounts");
if (!institutionAccounts) {
institutionAccounts = [];
}
this.setState({ institutionAccounts });
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
}
};
initState = async () => {
this.setState(this.cleanState);
};
// This should be the only method that writes state.transactions and saves transactions
// to the local storage.
// It does all necessary validations and steps to make sure state.transactions
// is always in a valid state.
setTransactions = async (transactions, saveToStorage = true) => {
// Make sure transactions are never undefined or null
if (!transactions) {
transactions = [];
}
if (saveToStorage) {
await saveItem(
(await this.getCurrentUser()).uid,
"transactions",
transactions
);
}
this.setState({
transactions: transactions
});
};
addTransaction = async (transaction = {}) => {
// returns an array of length 1
const result = await this.addTransactions([transaction]);
// return the first element (an object of length 1)
return result[0];
};
addTransactions = async newTransactionsData => {
const { transactions } = this.state;
let newTransactions = newTransactionsData.map(item =>
createNewTransaction(item)
);
// Only add transactions we don't have already
let updatedTransactionsList = _.uniqBy(
_.concat(transactions, newTransactions),
"id"
);
this.setTransactions(updatedTransactionsList);
return newTransactions;
};
getAccessTokenFromPublicToken = async publicToken => {
const getAccessTokenFromPublicToken = firebase
.functions()
.httpsCallable("getAccessTokenFromPublicToken_v6");
let result = await getAccessTokenFromPublicToken({
env: ENVIRONMENT,
public_token: publicToken
});
if (result.data.error) {
console.log(result);
throw result.data.error.error_message;
} else {
await this.addInstitutionAccount(
result.data.item_id,
result.data.institution_name,
result.data.account_details
);
}
};
// A note on dates:
// - Plaid uses the 'local' date as used by the bank and visible by the user on the bank website
// - By default, MomentJS uses the local timezone (e.g. the timezone of the user's device)
getPlaidTransactions = async () => {
let lastTransactionDate = this.getLastPlaidTransactionDate();
let startDate;
let endDate = moment().format("YYYY-MM-DD");
if (lastTransactionDate) {
// We subtract 2 days from the most recent transaction's date. This way, we're 100% sure that
// we won't miss any transactions.
// Why not 1 day? Because the maximum time difference between two locations is 27 hours
// (https://stackoverflow.com/questions/8131023/what-is-the-maximum-possible-time-zone-difference)
startDate = moment(lastTransactionDate)
.subtract(2, "days")
.format("YYYY-MM-DD");
} else {
// if no previous transactions
startDate = moment()
.subtract(5, "days")
.format("YYYY-MM-DD");
}
let plaidItemsToLoad = _(this.state.institutionAccounts)
.map(nextInstitutionAccount => nextInstitutionAccount.itemId)
.value();
try {
if (!plaidItemsToLoad || plaidItemsToLoad.length == 0) {
throw {
code: "NoItems"
};
}
const getPlaidTransactions = firebase
.functions()
.httpsCallable("getPlaidTransactions_v6");
let result = await getPlaidTransactions({
env: ENVIRONMENT,
start_date: startDate,
end_date: endDate,
plaidItemsToUse: plaidItemsToLoad
});
if (result.data.error) {
throw {
code: "PlaidError",
rawError: result.data.error
};
} else {
let itemTransactions = result.data.transactions;
const institutions = this.state.institutionAccounts;
const itemIdToNameMap = _.reduce(
institutions,
(acc, item) => {
return { ...acc, [item.itemId]: item.institutionName };
},
{}
);
const accounts = _.flatten(institutions.map(item => item.accounts));
const accountIdToNameMap = _.reduce(
accounts,
(acc, item) => {
return { ...acc, [item.accountId]: item.name };
},
{}
);
let newTransactions = [];
for (const nextItemTransaction of itemTransactions) {
const itemId = nextItemTransaction.item.item_id;
const plaidTransactions = nextItemTransaction.transactions;
if (plaidTransactions) {
for (let plaidTransaction of plaidTransactions) {
const {
name,
amount,
date,
pending,
account_id
} = plaidTransaction;
// Don't include pending transactions or income
if (pending || amount < 0) {
continue;
} else {
let transaction = {
id: calculateHashForPlaidTransaction(plaidTransaction),
source: "plaid",
name,
amount,
date,
account: accountIdToNameMap[account_id],
institution: itemIdToNameMap[itemId]
};
newTransactions = [...newTransactions, transaction];
}
}
}
}
// If the plaid output contains multiple transactions that are identical,
// update their hashes to be different
newTransactions = handleDuplicateHashTransactionsFromPlaid(
newTransactions
);
this.addTransactions(newTransactions);
return {
error: false,
transactions: newTransactions
};
}
} catch (error) {
console.log(error);
Sentry.captureException(error);
if (error.code) {
// Error has the following structure
// {code: 'errorIdentificationCode'}
switch (error.code) {
case "NoItems":
return {
error: true,
code: error.code,
message:
"Connect a bank or credit card account to automatically import expenses."
};
case "PlaidError":
return {
error: true,
code: error.code,
message: error.rawError
};
default:
return {
error: true,
code: "Unknown",
message: "Error occurred"
};
}
} else {
return {
error: true,
code: "Unknown",
message: error
};
}
}
};
listTransactions = () => {
return this.state.transactions.filter(
transaction => !transaction.isRemoved
);
};
updateTransaction = async attrs => {
const { transactions } = this.state;
const updatedTransactions = transactions.map(transaction => {
if (transaction.id === attrs.id) {
const { name, amount, category, date, notes } = attrs;
const updatedTransaction = {
...transaction,
name,
amount,
category,
date,
notes
};
// if it's a match, then return the updated transaction
return updatedTransaction;
}
// else, return the original transaction
return transaction;
});
this.setTransactions(updatedTransactions);
};
deleteTransaction = async id => {
const { transactions } = this.state;
const updatedTransactions = transactions.map(transaction => {
if (transaction.id === id) {
return {
...transaction,
isRemoved: true
};
} else {
return transaction;
}
});
this.setTransactions(updatedTransactions);
};
clearAllTransactions = async () => {
console.log("clearing all transactions...");
try {
removeItem((await this.getCurrentUser()).uid, "transactions");
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
this.setTransactions(null, false);
};
loadDummyData = async () => {
console.log("loading dummy data...");
const dummyData = defaultTransactions.map(t => ({
id: t.id,
source: t.source,
name: t.name,
amount: t.amount,
category: t.category,
date: t.date
}));
this.setTransactions(dummyData);
};
getLastPlaidTransactionDate = () => {
let lastTransaction = _(this.state.transactions)
.filter(item => {
return item.source === "plaid";
})
.sortBy("date")
.last();
if (lastTransaction) {
return lastTransaction.date;
} else {
return null;
}
};
addCategory = async newCategory => {
const { categories } = this.state;
const updatedCategoriesList = [...categories, newCategory];
await saveItem(
(await this.getCurrentUser()).uid,
"categories",
updatedCategoriesList
);
this.setState({
categories: updatedCategoriesList
});
return newCategory;
};
setNotificationTime = async newNotificationTime => {
await saveItem(
(await this.getCurrentUser()).uid,
"notificationTime",
newNotificationTime
);
this.setState({ notificationTime: newNotificationTime });
};
/**
* Schedules notifications for the next 7 days, based on the notificationTime of state.
* Will ask permission to the user if that was not yet granted.
*/
scheduleNotifications = async () => {
// First cancel any already scheduled notifications
this.cancelNotifications();
// Ask permission to send notifications if needed
// If permissions were not granted, the code below will just execute but not have any effect
const notificationStatus = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
// console.log("notification permission status:");
// console.log(notificationStatus);
// Calculate the time to send the next notification
let notificationDate = moment()
.hours(this.state.notificationTime.hours)
.minutes(this.state.notificationTime.minutes);
// Make sure this 'date' is after now
if (moment().diff(notificationDate) >= 0) {
notificationDate.add(1, "days");
}
notificationTitles = [
"Got a minute?",
"It's that time of day",
"Hey, you there?",
"Your day just got better",
"Do the right thing",
"The time has come",
"A friendly reminder",
"Money, money, money, money..."
];
notificationTitle =
notificationTitles[Math.floor(Math.random() * notificationTitles.length)];
let notification = {
title: notificationTitle,
body: "Review your recent expenses now to stay on top of your finances.",
ios: {
sound: true,
_displayInForeground: true
}
};
// Schedule the next 7 notifications
// If the time specified above has passed already, only 6 notifications will be scheduled
for (let i = 0; i < 7; i += 1) {
const nextNotificationDate = notificationDate.add(i, "days");
const response = await Notifications.scheduleLocalNotificationAsync(
notification,
{
time: nextNotificationDate.toDate()
}
);
// console.log(response);
}
};
cancelNotifications = async () => {
await Notifications.cancelAllScheduledNotificationsAsync();
};
registerUser = async (user, password) => {
try {
const userCredential = await firebase
.auth()
.createUserWithEmailAndPassword(user, password);
await this.loadStateFromStorage();
// Amplitude.setUserId(userId);
return {
success: true,
message: ""
};
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
return {
success: false,
message: error.message
};
}
};
loginUser = async (user, password) => {
try {
const userCredential = await firebase
.auth()
.signInWithEmailAndPassword(user, password);
await this.loadStateFromStorage();
return {
success: true,
message: ""
};
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
return {
success: false,
code: error.code,
message: error.message
};
}
};
logout = async () => {
try {
await firebase.auth().signOut();
Amplitude.setUserId(null);
// Clear the state
this.initState();
} catch (error) {
console.error(error);
Sentry.captureException(error);
}
};
isUserLoggedIn = async () => {
try {
let current_user = await this.getCurrentUser();
return current_user ? true : false;
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
return false;
}
};
// Get the current user, and wait for it if it was
// not initialized yet by firebase.
// https://github.com/firebase/firebase-js-sdk/issues/462
getCurrentUser = async () => {
const user = new Promise((resolve, reject) => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user);
}, reject);
});
return user;
};
addInstitutionAccount = async (itemId, institutionName, accounts) => {
try {
let institutionAccounts = this.state.institutionAccounts;
institutionAccounts.push({
itemId,
institutionName,
accounts
});
await saveItem(
(await this.getCurrentUser()).uid,
"institutionAccounts",
institutionAccounts
);
this.setState({ institutionAccounts });
} catch (error) {
console.log(error.message);
Sentry.captureException(error);
}
};
removeInstitutionAccount = async itemId => {
try {
// First remove in the database
await dbRemoveInstitutionAccount(
firebase,
(await this.getCurrentUser()).uid,
itemId
);
// Update the local state
const updatedInstitutionAccounts = _.filter(
this.state.institutionAccounts,
item => {
return item.itemId !== itemId;
}
);
await saveItem(
(await this.getCurrentUser()).uid,
"institutionAccounts",
updatedInstitutionAccounts
);
this.setState({ institutionAccounts: updatedInstitutionAccounts });
return {
error: false,
errorMessage: ""
};
} catch (error) {
console.log(error);
Sentry.captureException(error);
return {
error: true,
message: error
};
}
};
clearAsyncStorage = async () => {
await clearStorage();
};
getEnvironment = () => {
console.log("Your current environment is: " + ENVIRONMENT);
return ENVIRONMENT;
};
getUserEmail = async () => {
const currentUser = await this.getCurrentUser();
return currentUser.email;
};
sendPasswordresetEmail = async email => {
await firebase.auth().sendPasswordResetEmail(email);
};
render() {
return (
<GlobalContext.Provider
value={{
...this.state,
// Every function to update the state should be listed here:
loadStateFromStorage: this.loadStateFromStorage,
listTransactions: this.listTransactions,
addTransaction: this.addTransaction,
updateTransaction: this.updateTransaction,
deleteTransaction: this.deleteTransaction,
clearAllTransactions: this.clearAllTransactions,
loadDummyData: this.loadDummyData,
getAccessTokenFromPublicToken: this.getAccessTokenFromPublicToken,
getPlaidTransactions: this.getPlaidTransactions,
addCategory: this.addCategory,
setNotificationTime: this.setNotificationTime,
scheduleNotifications: this.scheduleNotifications,
cancelNotifications: this.cancelNotifications,
registerUser: this.registerUser,
loginUser: this.loginUser,
logout: this.logout,
isUserLoggedIn: this.isUserLoggedIn,
getCurrentUser: this.getCurrentUser,
removeInstitutionAccount: this.removeInstitutionAccount,
clearAsyncStorage: this.clearAsyncStorage,
getEnvironment: this.getEnvironment,
getUserEmail: this.getUserEmail,
sendPasswordresetEmail: this.sendPasswordresetEmail
}}
>
{this.props.children}
</GlobalContext.Provider>
);
}
}
export const withGlobalContext = ChildComponent => {
ComponentWithContext = props => (
<GlobalContext.Consumer>
{context => <ChildComponent {...props} global={context} />}
</GlobalContext.Consumer>
);
// necessary for retaining static properties (e.g. header titles)
hoistNonReactStatic(ComponentWithContext, ChildComponent);
return ComponentWithContext;
};