forked from Yasmataz/finpal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
741 lines (645 loc) · 22.2 KB
/
db.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
var { MongoClient, Logger } = require("mongodb");
var bcrypt = require("bcrypt"); //for password auth
var url = "mongodb+srv://dbUser:dbPassword@cluster0.rdapr.mongodb.net/cps888?retryWrites=true&w=majority";
var plan_name_edit = "";
if (process.env.TEST) {
url = "mongodb+srv://dbUser:dbPassword@cluster0.rdapr.mongodb.net/cps888-test?retryWrites=true&w=majority";
}
var db = null;
var client = null;
async function connect() {
if (db == null) {
var options = {useUnifiedTopology: true};
client = await MongoClient.connect(url, options);
if (process.env.TEST) {
client.db("cps888");
db = await client.db("cps888");
} else {
client.db("cps888");
db = await client.db("cps888");
}
}
return db;
}
async function register(name, username, password, role) {
var conn = await connect(); // establish connection with database
var SALT_ROUNDS = 10; // recomended value for hashing
var passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
const exsistingUser = await conn.collection('users').findOne({ username }); // pull from collection
const exsistingAdvisor = await conn.collection('advisors').findOne({ username });
if(exsistingUser != null || exsistingAdvisor != null){
throw new Error("Username already taken!");
}
if(role == 'user'){
await conn.collection('users').insertOne(
{
name,
username,
passwordHash,
financialProfile: {
plans : [],
pendingPlans : [],
totalFunds : 0
}
}
)
}else{
await conn.collection('advisors').insertOne(
{
name,
username,
passwordHash,
plans: [],
advisorType : "Budget Planner"
}
)
}
}
async function login(username, password) {
var conn = await connect();
var user = await conn.collection('users').findOne({ username });
var advisor = await conn.collection('advisors').findOne({ username });
if (user == null && advisor == null) {
throw new Error('Account does not exsist!');
}else if(user == null){
var valid = await bcrypt.compare(password, advisor.passwordHash);
var role = 'advisor';
}else{
var valid = await bcrypt.compare(password, user.passwordHash);
var role = 'user';
}
if (!valid) {
throw new Error("Invalid Password");
}
console.log("Login Successful!");
return role;
}
async function getFunds(username){
var conn = await connect();
const doc = await conn.collection('users')
.findOne({ username: username })
return doc.financialProfile.totalFunds;
}
async function getName(username){
var conn = await connect();
var user = await conn.collection('users').findOne({ username });
var advisor = await conn.collection('advisors').findOne({ username });
if (user == null && advisor == null) {
throw new Error('Username: '+username+' does not have a profile!');
}else if(user == null){
const doc = await conn.collection('advisors')
.findOne({ username });
return doc.name;
}else{
const doc = await conn.collection('users')
.findOne({ username });
return doc.name;
}
}
async function deleteAccount(username){
var conn = await connect();
await conn.collection('users').deleteOne({ username: username });
await conn.collection('advisors').deleteOne({ username: username });
return 0
}
async function getPlans(username, role) { // Returns all plans associated with a user
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
if (role == 'user') {
var user = await conn.collection('users').findOne({ username });
console.log(user)
var planIds = user.financialProfile.plans;
var plans = await Promise.all(planIds.map(async function(id){
var plan = await conn.collection('plans').findOne({"_id":ObjectId(id)});
return plan
}))
return plans;
} else {
var user = await conn.collection('advisors').findOne({ username });
var planIds = user.plans;
var plans = await Promise.all(planIds.map(async function(id) {
var plan = await conn.collection('plans').findOne({"_id":ObjectId(id)});
return plan
}))
return plans;
}
}
async function getPendingPlans(username) { // Returns all pending plans of given user
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
var user = await conn.collection('users').findOne({ username });
var planIds = user.financialProfile.pendingPlans;
var plans = await Promise.all(planIds.map(async function(id){
var plan = await conn.collection('plans').findOne({"_id":ObjectId(id)});
return plan
}))
return plans;
}
async function getPlanDetails(planID) { // Returns plan json associated with given ID
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
var plan = await conn.collection('plans').findOne({"_id":ObjectId(planID)})
return plan
}
function getNames(plans) { // Returns list of plan names given a list of plans
var names = plans.map(function(plan){
if (plan != null){
return plan.PlanName
}
})
return names;
}
function getId(user, plans, planName) { // Returns ID of a plan associated with a user given planName
var id = null
plans.forEach(function(plan) {
if (plan.PlanName == planName) {
id = plan._id;
}
});
return id;
}
async function deletePlan(username, planID, role) { // Removes given plan from user plan list, and deletes plan object
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
if (role == 'user') {
var user = await conn.collection('users').findOne({ username });
var planIds = user.financialProfile.plans;
var i = planIds.indexOf(planID.toString())
if (i > -1) {
planIds.splice(i,1)
}
const filter = { _id: user._id };
const updateDocument = {
$set: {
financialProfile: {
plans: planIds,
pendingPlans: user.financialProfile.pendingPlans,
totalFunds: user.financialProfile.totalFunds,
},
},
};
const result = await conn.collection('users').updateOne(filter, updateDocument);
} else {
var user = await conn.collection('advisors').findOne({ username });
var planIds = user.plans;
var i = planIds.indexOf(planID.toString())
if (i > -1) {
planIds.splice(i,1)
}
const filter = { _id: user._id };
const updateDocument = {
$set: {
plans: planIds,
},
};
const result = await conn.collection('advisors').updateOne(filter, updateDocument);
}
// Add this back in its just annoying to manually re-create plans so skipping the actual detele for now
//var plan = await conn.collection('plans').deleteOne({"_id":ObjectId(planID)});
}
async function deletePendingPlan(username, planID) { // Removes given plan from user pendingPlan list, and deletes plan object
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
var user = await conn.collection('users').findOne({ username });
var planIds = user.financialProfile.pendingPlans;
var i = planIds.indexOf(planID.toString())
if (i > -1) {
planIds.splice(i,1)
}
const filter = { _id: user._id };
const updateDocument = {
$set: {
financialProfile: {
plans: user.financialProfile.plans,
pendingPlans: planIds,
totalFunds: user.financialProfile.totalFunds,
},
},
};
const result = await conn.collection('users').updateOne(filter, updateDocument)
// Add this back in its just annoying to manually re-create plans so skipping the actual detele for now
//var plan = await conn.collection('plans').deleteOne({"_id":ObjectId(planID)});
}
async function acceptPlan(username, planID) { // Removes given plan ID from pending plan list, and adds to plans list for the user
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
var user = await conn.collection('users').findOne({ username });
// Remove from pending plans
var planIds = user.financialProfile.pendingPlans;
var i = planIds.indexOf(planID.toString())
if (i > -1) {
planIds.splice(i,1)
}
var filter = { _id: user._id };
var updateDocument = {
$set: {
financialProfile: {
plans: user.financialProfile.plans,
pendingPlans: planIds,
totalFunds: user.financialProfile.totalFunds,
},
},
};
var result = await conn.collection('users').updateOne(filter, updateDocument)
//add to plans
planIds = user.financialProfile.plans;
planIds.push(planID.toString())
filter = { _id: user._id };
updateDocument = {
$set: {
financialProfile: {
plans: planIds,
pendingPlans: user.financialProfile.pendingPlans,
totalFunds: user.financialProfile.totalFunds,
},
},
};
result = await conn.collection('users').updateOne(filter, updateDocument);
}
async function sendPlan(username, planID) { // Adds plan ID to users pending plans list
var conn = await connect();
var ObjectId = require('mongodb').ObjectID;
planID = planID.toString();
var user = await conn.collection('users').findOne({ username });
var planIds = user.financialProfile.pendingPlans;
planIds.push(planID)
const filter = { _id: user._id };
const updateDocument = {
$set: {
financialProfile: {
plans: user.financialProfile.plans,
pendingPlans: planIds,
totalFunds: user.financialProfile.totalFunds,
},
},
};
const result = await conn.collection('users').updateOne(filter, updateDocument);
}
async function addFunds(username, amount){
var conn = await connect();
var existingFunds = await getFunds(username);
console.log(existingFunds);
// console.log("input amount: "+ amount)
newAmount = +existingFunds + +amount;
// console.log("new funds"+ newAmount);
if (isNaN(existingFunds)){
await conn.collection('users').updateOne(
{username},
{
$set:{
"financialProfile.totalFunds": 0,
}
}
)
}else{
await conn.collection('users').updateOne(
{username},
{
$set:{
"financialProfile.totalFunds": newAmount,
}
}
)
}
console.log(await getFunds(username))
}
async function removeFunds(username, amount){
var conn = await connect();
var invalid;
var existingFunds = await getFunds(username);
console.log(existingFunds);
if (isNaN(existingFunds)){
await conn.collection('users').updateOne(
{username},
{
$set:{
"financialProfile.totalFunds": 0,
}
}
)
}else{
newAmount = +existingFunds - +amount;
// console.log("new funds"+ newAmount);
await conn.collection('users').updateOne(
{username},
{
$set:{
"financialProfile.totalFunds": newAmount,
}
}
)
}
console.log(await getFunds(username));
}
async function addPlan (username, role, PlanName, StartDate, EndDate){
var conn = await connect();
var plan;
if (role == 'user') {
var user = await conn.collection('users').findOne({ username });
var plan = await conn.collection('plans').insertOne(
{
PlanName,
StartDate,
EndDate,
totalSpent: 0,
categories: []
}
)
var new_id = plan.insertedId;
var planIds = user.financialProfile.plans;
planIds.push(new_id.toString())
filter = { _id: user._id };
updateDocument = {
$set: {
financialProfile: {
plans: planIds,
pendingPlans: user.financialProfile.pendingPlans,
totalFunds: user.financialProfile.totalFunds,
},
},
};
result = await conn.collection('users').updateOne(filter, updateDocument);
}
else{
var advisor = await conn.collection('advisors').findOne({ username });
var plan = await conn.collection('plans').insertOne(
{
PlanName,
StartDate,
EndDate,
totalSpent: 0,
categories: []
}
)
new_id = plan.insertedId
planIds = advisor.plans;
planIds.push(new_id.toString())
filter = { _id: advisor._id };
updateDocument = {
$set: {
plans: planIds,
},
};
result = await conn.collection('advisors').updateOne(filter, updateDocument);
}
}
async function getLatestPlan(username, role){
var conn = await connect();
if (role =='user'){
var user = await conn.collection('users').findOne({ username });
var planIds = user.financialProfile.plans;
l = planIds.length
index = l-1
var _id = ""+planIds[index];
return _id;
}
else{
var advisor = await conn.collection('advisors').findOne({ username });
var planIds = advisor.plans;
l = planIds.length
index = l-1
var _id = ""+planIds[index];
return _id;
}
}
async function addCategory (username, role, Budgeted, Spent, CategoryName){
var conn = await connect();
var _id = await getLatestPlan(username, role);
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(_id);
var plan = await conn.collection('plans').findOne({_id:ObjectId(_id)})
console.log(plan)
await conn.collection('plans').update(
{_id: id_obj},
{$addToSet: {
categories: {budgeted: Budgeted, spent: Spent, name: CategoryName}
}
}
)
var total_spent = +parseFloat(plan.totalSpent) + parseFloat(Spent);
await conn.collection('plans').update(
{_id: id_obj},
{$set:{
totalSpent: total_spent,
}
}
)
}
async function getLatestCategoriesName(username, role){
var conn = await connect();
var _id = await getLatestPlan(username, role);
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(_id);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
var category_list = plan.categories;
console.log(category_list);
return category_list;
//return category_list.map(({name}) => name);
}
async function deleteCategory(username, role, categoryname){
var conn = await connect();
var _id = await getPlan(username, role);
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(_id);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
var category_list = plan.categories;
var category_name = category_list.map(({name}) => name);
var category_spent = category_list.map(({spent}) => spent);
console.log("NAME" +category_name);
console.log(categoryname);
var i = category_name.indexOf(categoryname)
console.log(i)
sub_spent = category_spent[i]
console.log(sub_spent)
if (i > -1) {
category_list.splice(i,1)
}
console.log(category_list);
const filter = { _id: id_obj };
const updateDocument = {
$set: {
categories: category_list
},
}
result = await conn.collection('plans').updateOne(filter, updateDocument);
var total_spent = +parseFloat(plan.totalSpent) + -parseFloat(sub_spent);
await conn.collection('plans').update(
{_id: id_obj},
{$set:{
totalSpent: total_spent,
}
}
)
}
async function savePlanName(PlanName){
plan_name_edit = PlanName;
console.log("saveplanname" + PlanName)
}
async function getPlanName(){
console.log("getplaname:"+ plan_name_edit)
return plan_name_edit;
}
async function clearPlanName(){
plan_name_edit = "";
}
async function getCategories(PlanId){
var conn = await connect();
var ObjectId = require('mongodb').ObjectId;
console.log("plan id: ", PlanId)
var id_obj = ObjectId(PlanId);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
console.log("getcategoriesplan" + plan)
var category_list = plan.categories;
console.log("categories")
console.log(category_list);
return category_list;
}
async function editPlan (username, role, new_plan_name, new_start_date, new_end_date){
var conn = await connect();
var planName = await getPlanName();
var plans = await getPlans(username, role)
var planID = await getId(username, plans, planName);
console.log(planID)
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(planID);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
if (new_plan_name == null || new_plan_name==""){
new_plan_name = plan.PlanName
}
if (new_start_date == null|| new_start_date==""){
new_start_date = plan.StartDate
}
if (new_end_date == null|| new_end_date==""){
new_end_date = plan.EndDate
}
await conn.collection('plans').update(
{_id: id_obj},
{$set:{
PlanName: new_plan_name,
StartDate: new_start_date,
EndDate: new_end_date
}
}
)
}
async function deleteEditCategory(username, role, categoryname){
var conn = await connect();
var planName = await getPlanName();
var plans = await getPlans(username, role)
var planID = await getId(username, plans, planName);
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(planID);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
var category_list = plan.categories;
var category_name = category_list.map(({name}) => name);
var category_spent = category_list.map(({spent}) => spent);
console.log("NAME" +category_name);
console.log(categoryname);
var i = category_name.indexOf(categoryname)
console.log(i)
sub_spent = category_spent[i]
console.log(sub_spent)
if (i > -1) {
category_list.splice(i,1)
}
console.log(category_list);
const filter = { _id: id_obj };
const updateDocument = {
$set: {
categories: category_list
},
}
result = await conn.collection('plans').updateOne(filter, updateDocument);
var total_spent = +parseFloat(plan.totalSpent) + -parseFloat(sub_spent);
await conn.collection('plans').update(
{_id: id_obj},
{$set:{
totalSpent: total_spent,
}
}
)
}
async function editCategory (username, role, categoryname, new_cat_name, new_budget, new_spent){
var conn = await connect();
var planName = await getPlanName();
var plans = await getPlans(username, role)
var planID = await getId(username, plans, planName);
var ObjectId = require('mongodb').ObjectId;
var id_obj = ObjectId(planID);
var plan = await conn.collection('plans').findOne({_id:ObjectId(id_obj)})
var category_list = plan.categories;
var category_name = category_list.map(({name}) => name);
var category_spent = category_list.map(({spent}) => spent);
var category_budget = category_list.map(({budgeted}) => budgeted);
var i = category_name.indexOf(categoryname)
sub_spent = category_spent[i]
if (new_cat_name[i] == null || new_cat_name[i]==""){
new_cat_name[i] = category_name[i]
}
if (new_budget[i] == null|| new_budget[i]==""){
new_budget[i] = category_budget[i]
}
if (new_spent[i] == null|| new_spent[i]==""){
new_spent[i] = category_spent[i]
}
category_list[i] = {budgeted: new_budget[i], spent: new_spent[i], name: new_cat_name[i]}
const filter = { _id: id_obj };
const updateDocument = {
$set: {
categories: category_list
},
}
result = await conn.collection('plans').updateOne(filter, updateDocument);
var total_spent = +parseFloat(plan.totalSpent) + -parseFloat(sub_spent) + parseFloat(new_spent[i]);
await conn.collection('plans').update(
{_id: id_obj},
{$set:{
totalSpent: total_spent,
}
}
)
}
async function close(){
await client.close();
}
module.exports = {
url,
login,
register,
getPlans,
getPendingPlans,
getId,
getNames,
getPlanDetails,
deletePlan,
deletePendingPlan,
acceptPlan,
sendPlan,
getFunds,
deleteAccount,
getName,
addFunds,
removeFunds,
addPlan,
getLatestPlan,
addCategory,
getLatestCategoriesName,
deleteCategory,
savePlanName,
getPlanName,
clearPlanName,
getCategories,
deleteCategory,
editPlan,
editCategory,
deleteEditCategory,
close
};
async function wipe() {
var conn = await connect();
conn.collection("users").drop();
conn.collection("advisors").drop();
}
if (process.env.TEST) {
module.exports.wipe = wipe;
}