-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb_routes.js
More file actions
4544 lines (4194 loc) · 143 KB
/
db_routes.js
File metadata and controls
4544 lines (4194 loc) · 143 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
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Imports
const UserAuth = require("./user_auth");
const db_router = require("express").Router();
const { validationResult, body } = require("express-validator");
const PDFDoc = require("pdfkit");
const fs = require("fs");
const fse = require("fs-extra");
const path = require("path");
const moment = require("moment");
const fileSizeParser = require("filesize-parser");
const he = require("he");
const { convert } = require("html-to-text");
const redeployDatabase = require("../../db_setup");
function humanFileSize(bytes, si = false, dp = 1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + " B";
}
const units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (
Math.round(Math.abs(bytes) * r) / r >= thresh &&
u < units.length - 1
);
return bytes.toFixed(dp) + " " + units[u];
}
const defaultFileSizeLimit = 15 * 1024 * 1024;
const DB_CONFIG = require("../database/db_config");
const CONFIG = require("../config/config");
const { nanoid } = require("nanoid");
const CONSTANTS = require("../consts");
const { ROLES } = require("../consts");
const { off } = require("process");
const USERAuth = require("./user_auth");
const ACTION_TARGETS = {
ADMIN: "admin",
COACH: "coach",
TEAM: "team",
INDIVIDUAL: "individual",
COACH_ANNOUNCEMENT: "coach_announcement",
STUDENT_ANNOUNCEMENT: "student_announcement",
PEER_EVALUATION: "peer_evaluation",
};
// Routes
module.exports = (db) => {
/**
* /getAllUsersForLogin ENDPOINT SHOULD ONLY BE HIT IN DEVELOPMENT ONLY
*
* THIS IS USED BY THE DEVELOPMENT LOGIN AND SHOULD NOT BE USED FOR ANYTHING ELSE
*/
if (process.env.NODE_ENV !== "production") {
// gets all users
db_router.get("/DevOnlyGetAllUsersForLogin", (req, res) => {
db.query(`SELECT ${CONSTANTS.SIGN_IN_SELECT_ATTRIBUTES} FROM users`).then(
(users) => res.send(users),
);
});
//Redeploy database
db_router.put("/DevOnlyRedeployDatabase", async (req, res) => {
try {
await redeployDatabase();
res
.status(200)
.json({ success: true, message: "Database redeployed successfully" });
} catch (error) {
res.status(500).json({
success: false,
message: "Failed to redeploy database",
error: error.message,
});
}
});
}
// Debug route to force an error to be logged by the error handler
db_router.get("/forceError", (req, res, next) => {
// cause some js error
nonExistentFunction();
});
// get error logs
db_router.get("/getAllErrorLogs", [UserAuth.isAdmin], (req, res, next) => {
const getErrorLogsQuery = `
SELECT * FROM ${DB_CONFIG.tableNames.error_log} ORDER BY error_log_id ASC
`;
db.query(getErrorLogsQuery)
.then((errorLogs) => {
res.send(errorLogs);
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
});
db_router.delete(
"/removeErrorLog/:id",
[UserAuth.isAdmin],
(req, res, next) => {
const deleteErrorLogQuery = `
DELETE FROM ${DB_CONFIG.tableNames.error_log} WHERE error_log_id = ?
`;
db.query(deleteErrorLogQuery, [req.params.id])
.then(() => {
res.status(200).send();
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/selectAllSponsorInfo",
[UserAuth.isCoachOrAdmin],
(req, res) => {
db.selectAll(DB_CONFIG.tableNames.sponsor_info).then(function (value) {
res.send(value);
});
},
);
db_router.get(
"/selectAllStudentInfo",
[UserAuth.isCoachOrAdmin],
(req, res, next) => {
let getStudentsQuery = `
SELECT *
FROM users
LEFT JOIN semester_group
ON users.semester_group = semester_group.semester_id
WHERE type = 'student'
ORDER BY semester_group desc
`;
db.query(getStudentsQuery)
.then((values) => {
res.send(values);
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/selectAllNonStudentInfo",
[UserAuth.isAdmin],
(req, res, next) => {
let getUsersQuery = `
SELECT *
FROM users
LEFT JOIN semester_group
ON users.semester_group = semester_group.semester_id
WHERE type != 'student'
`;
db.query(getUsersQuery)
.then((values) => {
res.send(values);
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getSemesterStudents",
[UserAuth.isSignedIn],
(req, res, next) => {
let query = "";
let params = [];
switch (req.user.type) {
//Retrieves all users from a semester group that is similar to the student that is making the query.
case ROLES.STUDENT:
query = `
SELECT users.*
FROM users
WHERE users.semester_group = (
SELECT semester_group FROM users WHERE system_id = ?
) AND users.type = 'student'`;
params = [req.user.system_id];
break;
case ROLES.COACH:
query = `
SELECT users.* FROM users
LEFT JOIN semester_group
ON users.semester_group = semester_group.semester_id
WHERE users.semester_group IN (
SELECT projects.semester FROM projects
WHERE projects.project_id IN (
SELECT project_coaches.project_id FROM project_coaches
WHERE project_coaches.coach_id = ?
)
)`;
params = [req.user.system_id];
break;
case ROLES.ADMIN:
query = `SELECT * FROM users
LEFT JOIN semester_group
ON users.semester_group = semester_group.semester_id
WHERE users.type = 'student'`;
break;
default:
break;
}
db.query(query, params)
.then((users) => {
if (req.user.type === ROLES.STUDENT) {
users = users.map((user) => {
let output = {};
if (user.project === req.user.project) {
output["last_login"] = user["last_login"];
output["prev_login"] = user["prev_login"];
}
output["active"] = user["active"];
output["email"] = user["email"];
output["fname"] = user["fname"];
output["lname"] = user["lname"];
output["project"] = user["project"];
output["semester_group"] = user["semester_group"];
output["system_id"] = user["system_id"];
output["type"] = user["type"];
return output;
});
}
res.send(users);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get("/getProjectMembers", [UserAuth.isSignedIn], (req, res) => {
let query = `SELECT users.*, project_coaches.project_id FROM users
LEFT JOIN project_coaches ON project_coaches.coach_id = users.system_id
WHERE users.project = ? OR project_coaches.project_id = ?`;
params = [req.query.project_id, req.query.project_id];
db.query(query, params).then((users) => res.send(users));
});
// NOTE: This is currently used for getting user for AdminView to mock users, however, I feel that this network request will get quite large
// as we add about 100 users every semester.
db_router.get("/getActiveUsers", [UserAuth.isAdmin], (req, res) => {
let query = `SELECT ${CONSTANTS.SIGN_IN_SELECT_ATTRIBUTES}
FROM users
WHERE active = ''`;
db.query(query).then((users) => res.send(users));
});
db_router.post(
"/createUser",
[
UserAuth.isAdmin,
UserAuth.canWrite,
body("system_id")
.not()
.isEmpty()
.trim()
.escape()
.withMessage("Cannot be empty")
.isLength({ max: 50 }),
body("fname")
.not()
.isEmpty()
.trim()
.escape()
.withMessage("Cannot be empty")
.isLength({ max: 50 }),
body("lname")
.not()
.isEmpty()
.trim()
.escape()
.withMessage("Cannot be empty")
.isLength({ max: 50 }),
body("email")
.not()
.isEmpty()
.trim()
.escape()
.withMessage("Cannot be empty")
.isLength({ max: 50 }),
body("type")
.not()
.isEmpty()
.trim()
.escape()
.withMessage("Cannot be empty")
.isLength({ max: 50 }),
body("semester_group").isLength({ max: 50 }),
body("project").isLength({ max: 50 }),
body("active").trim().escape().isLength({ max: 50 }),
body("viewOnly").trim().escape().isLength({ max: 50 }),
],
async (req, res, next) => {
let result = validationResult(req);
console.log(result);
if (result.errors.length !== 0) {
const error = new Error("Validation Error");
error.statusCode = 400;
return next(error);
}
let body = req.body;
const sql = `INSERT INTO ${DB_CONFIG.tableNames.users}
(system_id, fname, lname, email, type, semester_group, project, active, view_only, profile_info)
VALUES (?,?,?,?,?,?,?,?,?,?)`;
const active =
body.active === "false"
? moment().format(CONSTANTS.datetime_format)
: "";
const viewOnly = body.viewOnly === "true" ? "TRUE" : "FALSE";
// Default profile_info with required fields
const defaultProfileInfo = JSON.stringify({
additional_info: "",
dark_mode: false,
gantt_view: true,
});
const params = [
body.system_id,
body.fname,
body.lname,
body.email,
body.type,
body.semester_group === "" ? null : body.semester_group,
body.project === "" ? null : body.project,
active,
viewOnly,
defaultProfileInfo,
];
db.query(sql, params)
.then(() => {
return res.status(200).send();
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.post(
"/batchCreateUser",
[
UserAuth.isAdmin,
UserAuth.canWrite,
// TODO: Add more validation
],
async (req, res, next) => {
try {
let users = JSON.parse(req.body.users);
const failedUsers = [];
const successUsers = [];
for (const user of users) {
// Default profile_info with required fields
const defaultProfileInfo = JSON.stringify({
additional_info: "",
dark_mode: false,
gantt_view: true,
});
const values = [
user.system_id,
user.fname,
user.lname,
user.email,
user.type,
user.semester_group === "" ? null : user.semester_group,
user.active.toLocaleLowerCase() === "false"
? moment().format(CONSTANTS.datetime_format)
: "",
defaultProfileInfo,
];
try {
await db.query(
`INSERT INTO ${DB_CONFIG.tableNames.users}
(system_id, fname, lname, email, type, semester_group, active, profile_info)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
values,
);
successUsers.push(user);
} catch (err) {
let errorMessage = err.message;
// Provide more user-friendly error messages for common constraint violations
if (err.code === "SQLITE_CONSTRAINT") {
if (
err.message.includes(
"UNIQUE constraint failed: users.system_id",
)
) {
errorMessage = `System ID '${user.system_id}' already exists`;
} else if (
err.message.includes("UNIQUE constraint failed: users.email")
) {
errorMessage = `Email '${user.email}' already exists`;
} else {
errorMessage = "Duplicate data - user may already exist";
}
}
failedUsers.push({ user, error: errorMessage });
}
}
res.status(200).json({ successUsers, failedUsers });
} catch (err) {
const error = new Error(err);
error.statusCode = 500;
return next(error);
}
},
);
db_router.post(
"/editUser",
[UserAuth.isAdmin, UserAuth.canWrite],
(req, res, next) => {
let body = req.body;
let updateQuery = `
UPDATE users
SET fname = ?,
lname = ?,
email = ?,
type = ?,
semester_group = ?,
project = ?,
active = ?,
view_only = ?
WHERE system_id = ?
`;
const active =
body.active === "false"
? moment().format(CONSTANTS.datetime_format)
: "";
const viewOnly = body.viewOnly === "true" ? "TRUE" : "FALSE";
let params = [
body.fname,
body.lname,
body.email,
body.type,
body.semester_group || null,
body.project || null,
active,
viewOnly,
body.system_id,
];
db.query(updateQuery, params)
.then(() => {
return res.status(200).send();
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.post(
"/removeTime",
[UserAuth.isSignedIn, UserAuth.canWrite],
(req, res, next) => {
if (!req.body.id) {
const error = new Error("No Id Provided");
error.statusCode = 400;
return next(error);
}
const sql = "UPDATE time_log SET active=0 WHERE time_log_id = ?";
db.query(sql, [req.body.id])
.then(() => {
res.status(200).send();
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get("/avgTime", [UserAuth.isSignedIn], async (req, res, next) => {
const sql =
"SELECT ROUND(AVG(CASE WHEN active != 0 THEN time_amount ELSE NULL END), 2) AS avgTime, system_id FROM time_log WHERE project = ? GROUP BY system_id";
console.log(req.query.project_id);
db.query(sql, [req.query.project_id])
.then((time) => {
console.log(time);
res.send(time);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
});
db_router.post(
"/createTimeLog",
[UserAuth.canWrite],
async (req, res, next) => {
let result = validationResult(req);
if (result.errors.length !== 0) {
const error = new Error("Validation Error");
error.statusCode = 400;
return next(error);
}
// Validate that the work date is not in the future
// This prevents users from logging time for dates that haven't occurred yet
const workDate = new Date(req.body.date);
const currentDate = new Date();
const currentDateOnly = new Date(
currentDate.getFullYear(),
currentDate.getMonth(),
currentDate.getDate(),
);
const workDateOnly = new Date(
workDate.getFullYear(),
workDate.getMonth(),
workDate.getDate(),
);
if (workDateOnly > currentDateOnly) {
const error = new Error("Cannot log time for future dates");
error.statusCode = 400;
return next(error);
}
// Validate that the work date is within the past 14 days (2 weeks)
// This maintains the existing business rule about recent time logging
const twoWeeksAgo = new Date(currentDateOnly);
twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14);
if (workDateOnly < twoWeeksAgo) {
const error = new Error("Cannot log time for dates older than 14 days");
error.statusCode = 400;
return next(error);
}
let mock_id = req.user.mock ? req.user.mock.system_id : "";
const sql = `INSERT INTO time_log
(semester, system_id, project, mock_id, work_date, time_amount, work_comment)
VALUES (?,?,?,?,?,?,?)`;
const params = [
req.user.semester_group,
req.user.system_id,
req.user.project,
mock_id,
req.body.date,
req.body.time_amount,
req.body.comment,
];
db.query(sql, params)
.then(() => {
return res.status(200).send();
})
.catch((err) => {
console.error(err);
let error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getActiveProjects",
[UserAuth.isSignedIn],
(req, res, next) => {
let getProjectsQuery = `
SELECT *
FROM projects
LEFT JOIN semester_group
ON projects.semester = semester_group.semester_id
WHERE projects.semester IS NOT NULL
`;
db.query(getProjectsQuery)
.then((values) => {
res.send(values);
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getActiveCoaches",
[UserAuth.isCoachOrAdmin],
(req, res, next) => {
const sql = `SELECT * FROM users WHERE type = '${ROLES.COACH}' AND active = ''`;
db.query(sql)
.then((coaches) => {
res.send(coaches);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getProjectCoaches",
[UserAuth.isCoachOrAdmin],
(req, res, next) => {
const getProjectCoaches = `SELECT users.* FROM users
LEFT JOIN project_coaches ON project_coaches.coach_id = users.system_id
WHERE project_coaches.project_id = ?`;
db.query(getProjectCoaches, [req.query.project_id])
.then((coaches) => {
res.send(coaches);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getProjectStudents",
[UserAuth.isCoachOrAdmin],
(req, res, next) => {
const getProjectStudents = "SELECT * FROM users WHERE users.project = ?";
db.query(getProjectStudents, [req.query.project_id])
.then((students) => {
res.send(students);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getProjectStudentNames",
[UserAuth.isSignedIn],
(req, res, next) => {
const getProjectStudents =
"SELECT fname,lname FROM users WHERE users.project = ? and users.system_id!=?";
db.query(getProjectStudents, [req.query.project_id, req.user.system_id])
.then((students) => {
res.send(students);
})
.catch((err) => {
console.error(err);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/selectAllCoachInfo",
[UserAuth.isCoachOrAdmin],
(req, res, next) => {
const getCoachInfoQuery = `
SELECT users.system_id,
users.fname,
users.lname,
users.email,
users.semester_group,
(
SELECT "[" || group_concat(
"{" ||
"""title""" || ":" || """" || COALESCE(projects.display_name, projects.title) || """" || "," ||
"""semester_id""" || ":" || """" || projects.semester || """" || "," ||
"""project_id""" || ":" || """" || projects.project_id || """" || "," ||
"""organization""" || ":" || """" || projects.organization || """" || "," ||
"""status""" || ":" || """" || projects.status || """" ||
"}"
) || "]"
FROM project_coaches
LEFT JOIN projects ON projects.project_id = project_coaches.project_id
WHERE project_coaches.coach_id = users.system_id
) projects
FROM users
WHERE users.type = "${ACTION_TARGETS.COACH}"
`;
db.query(getCoachInfoQuery)
.then((coaches) => {
res.send(coaches);
})
.catch((err) => {
console.error(error);
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
// used in the /projects page and home page if featured
db_router.get("/getActiveArchiveProjects", (req, res, next) => {
const { resultLimit, page, featured } = req.query;
let skipNum = page * resultLimit;
let projectsQuery;
let rowCountQuery;
if (featured === "true") {
// home page - randomized order of projects
projectsQuery = `SELECT * FROM ${DB_CONFIG.tableNames.archive} WHERE oid NOT IN
( SELECT oid FROM ${DB_CONFIG.tableNames.archive} ORDER BY random() LIMIT ? )
AND inactive = '' AND featured = 1 ORDER BY random() LIMIT ?`;
rowCountQuery = `SELECT COUNT(*) FROM ${DB_CONFIG.tableNames.archive} WHERE inactive = ''`;
} else {
// projects page - all archived projects data regardless if they are archived or not
projectsQuery = `SELECT * FROM ${DB_CONFIG.tableNames.archive} WHERE oid NOT IN
( SELECT oid FROM ${DB_CONFIG.tableNames.archive} ORDER BY archive_id LIMIT ? )
AND inactive = '' ORDER BY archive_id LIMIT ?`;
rowCountQuery = `SELECT COUNT(*) FROM ${DB_CONFIG.tableNames.archive} WHERE inactive = ''`;
}
const projectsPromise = db.query(projectsQuery, [skipNum, resultLimit]);
const rowCountPromise = db.query(rowCountQuery);
Promise.all([rowCountPromise, projectsPromise])
.then(([[rowCount], projects]) => {
res.send({
totalProjects: rowCount[Object.keys(rowCount)[0]],
projects: projects,
});
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
});
// endpoint for getting ALL archive data to view within admin view/editor
db_router.get("/getArchiveProjects", (req, res, next) => {
const { resultLimit, offset } = req.query;
let skipNum = offset * resultLimit;
let projectsQuery = `SELECT * FROM ${DB_CONFIG.tableNames.archive} WHERE
oid NOT IN (SELECT oid FROM ${DB_CONFIG.tableNames.archive} ORDER BY archive_id LIMIT ?)
ORDER BY archive_id LIMIT ?`;
let rowCountQuery = `SELECT COUNT(*) FROM ${DB_CONFIG.tableNames.archive}`;
const projectsPromise = db.query(projectsQuery, [skipNum, resultLimit]);
const rowCountPromise = db.query(rowCountQuery);
Promise.all([rowCountPromise, projectsPromise])
.then(([[rowCount], projects]) => {
res.send({
totalProjects: rowCount[Object.keys(rowCount)[0]],
projects: projects,
});
})
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
});
/**
* Responds with projects from database
*
* TODO: Add pagination
*/
db_router.get(
"/getProjects",
[UserAuth.isCoachOrAdmin],
async (req, res, next) => {
const query = "SELECT * from projects";
db.query(query)
.then((projects) => res.send(projects))
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getCandidateProjects",
[UserAuth.isSignedIn],
async (req, res, next) => {
const query =
"SELECT * from projects WHERE projects.status = 'candidate';";
db.query(query)
.then((projects) => res.send(projects))
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.get(
"/getMyProjects",
[UserAuth.isSignedIn],
async (req, res, next) => {
let query;
let params;
switch (req.user.type) {
case ROLES.COACH:
query = `SELECT projects.*
FROM projects
INNER JOIN project_coaches
ON (projects.project_id = project_coaches.project_id AND project_coaches.coach_id = ?);`;
params = [req.user.system_id];
break;
case ROLES.STUDENT:
query = `SELECT users.system_id, users.semester_group, projects.*
FROM users
INNER JOIN projects
ON users.system_id = ? AND projects.project_id = users.project;`;
params = [req.user.system_id];
break;
case ROLES.ADMIN:
query =
"SELECT * FROM projects WHERE projects.status NOT IN ('completed', 'rejected', 'archive');";
params = [];
break;
default:
const error = new Error(
"Invalid user type...something must be very very broken...",
);
error.statusCode = 500;
return next(error);
}
db.query(query, params)
.then((proposals) => res.send(proposals))
.catch((err) => res.status(500).send(err));
},
);
db_router.get(
"/getSemesterProjects",
[UserAuth.isSignedIn],
async (req, res, next) => {
let query;
let params;
switch (req.user.type) {
case ROLES.COACH:
query = `
SELECT projects.*
FROM projects
WHERE projects.semester IN
(SELECT projects.semester
FROM projects
INNER JOIN project_coaches
ON (projects.project_id = project_coaches.project_id AND project_coaches.coach_id = ?))
;`;
params = [req.user.system_id];
break;
case ROLES.STUDENT:
query = `SELECT users.system_id, projects.*
FROM users
INNER JOIN projects
ON users.system_id = ? AND projects.semester = users.semester_group;`;
params = [req.user.system_id];
break;
case ROLES.ADMIN:
query =
"SELECT * FROM projects WHERE projects.status NOT IN ('in progress', 'completed', 'rejected', 'archive');";
params = [];
break;
default:
const error = new Error(
"Invalid user type...something must be very very broken...",
);
error.statusCode = 500;
return next(error);
}
db.query(query, params)
.then((projects) => res.send(projects))
.catch((err) => {
const error = new Error(err);
error.statusCode = 500;
return next(error);
});
},
);
db_router.post(
"/editArchive",
[UserAuth.isAdmin, UserAuth.canWrite],
async (req, res, next) => {
let body = req.body;
const updateArchiveQuery = `UPDATE ${DB_CONFIG.tableNames.archive}
SET featured=?, outstanding=?, creative=?, priority=?,
title=?, project_id=?, team_name=?,
members=?, sponsor=?, coach=?,
poster_thumb=?, poster_full=?, archive_image=?, synopsis=?,
video=?, name=?, dept=?,
start_date=?, end_date=?, keywords=?, url_slug=?, inactive=?, locked=?
WHERE archive_id = ?`;
const inactive =
body.inactive === "true"
? moment().format(CONSTANTS.datetime_format)
: "";
const locked =
body.locked === "true"
? req.user.fname +
" " +
req.user.lname +
" locked at " +
moment().format(CONSTANTS.datetime_format)
: "";
const checkBox = (data) => {
if (data === "true" || data === "1") {
return 1;
}
return 0;
};
const strToInt = (data) => {
if (typeof data === "string") {
return parseInt(data);
}
return 0;
};
let updateArchiveParams = [
checkBox(body.featured),
checkBox(body.outstanding),
checkBox(body.creative),
strToInt(body.priority),
body.title,
body.project_id,
body.team_name,
body.members,
body.sponsor,
body.coach,
body.poster_thumb,