-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1175 lines (1008 loc) · 47.2 KB
/
Copy pathmain.cpp
File metadata and controls
1175 lines (1008 loc) · 47.2 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
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <mutex>
#include <mysql/mysql.h>
#include <json/json.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <iomanip>
#include <ctime>
#include <chrono>
#include <sstream>
using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;
// Interval Tree Node for scheduling
struct Interval {
int start, end;
int id;
string data;
Interval(int s, int e, int i, string d) : start(s), end(e), id(i), data(d) {}
};
class IntervalTreeNode {
public:
Interval interval;
int max_end;
IntervalTreeNode* left;
IntervalTreeNode* right;
IntervalTreeNode(Interval i) : interval(i), max_end(i.end), left(nullptr), right(nullptr) {}
};
class IntervalTree {
private:
IntervalTreeNode* root;
IntervalTreeNode* insert(IntervalTreeNode* root, Interval interval) {
if (!root) return new IntervalTreeNode(interval);
int low = interval.start;
if (low < root->interval.start) {
root->left = insert(root->left, interval);
} else {
root->right = insert(root->right, interval);
}
if (root->max_end < interval.end) {
root->max_end = interval.end;
}
return root;
}
bool doOverlap(Interval i1, Interval i2) {
return (i1.start < i2.end && i2.start < i1.end);
}
Interval* overlapSearch(IntervalTreeNode* root, Interval i) {
if (!root) return nullptr;
if (doOverlap(root->interval, i)) {
return &(root->interval);
}
if (root->left && root->left->max_end >= i.start) {
return overlapSearch(root->left, i);
}
return overlapSearch(root->right, i);
}
public:
IntervalTree() : root(nullptr) {}
void insert(Interval interval) {
root = insert(root, interval);
}
bool hasConflict(Interval interval) {
return overlapSearch(root, interval) != nullptr;
}
};
// Graph for student-course relationships
class Graph {
private:
map<int, vector<int>> adj_list;
public:
void addEdge(int student_id, int course_id) {
adj_list[student_id].push_back(course_id);
}
vector<int> getStudentCourses(int student_id) {
if (adj_list.find(student_id) != adj_list.end()) {
return adj_list[student_id];
}
return {};
}
vector<int> getCourseStudents(int course_id) {
vector<int> students;
for (const auto& pair : adj_list) {
for (int course : pair.second) {
if (course == course_id) {
students.push_back(pair.first);
break;
}
}
}
return students;
}
// Find shortest path between students (through common courses)
vector<int> findPath(int start_student, int end_student) {
if (start_student == end_student) return {start_student};
queue<int> q;
map<int, int> parent;
set<int> visited;
q.push(start_student);
visited.insert(start_student);
parent[start_student] = -1;
while (!q.empty()) {
int current = q.front();
q.pop();
vector<int> courses = getStudentCourses(current);
for (int course : courses) {
vector<int> course_students = getCourseStudents(course);
for (int student : course_students) {
if (visited.find(student) == visited.end()) {
visited.insert(student);
parent[student] = current;
q.push(student);
if (student == end_student) {
vector<int> path;
int curr = end_student;
while (curr != -1) {
path.push_back(curr);
curr = parent[curr];
}
reverse(path.begin(), path.end());
return path;
}
}
}
}
}
return {};
}
const map<int, vector<int>>& getAdjList() const { return adj_list; }
};
// Database Manager
class DatabaseManager {
private:
mutex db_mutex;
MYSQL* connection;
void ensureConnection() {
if (!connection || mysql_ping(connection)) {
cerr << "🔁 Reconnecting to MySQL...\n";
if (connection) mysql_close(connection);
connection = mysql_init(nullptr);
if (!connection) {
throw runtime_error("MySQL initialization failed");
}
if (!mysql_real_connect(connection, "localhost", "root", "password",
"school_management2", 0, NULL, 0)) {
string error_msg = mysql_error(connection);
mysql_close(connection);
connection = nullptr;
throw runtime_error("Database connection failed: " + error_msg);
}
cout << "✅ Connected to MySQL database\n";
}
}
public:
DatabaseManager() : connection(nullptr) {
ensureConnection();
}
~DatabaseManager() {
if (connection) {
mysql_close(connection);
connection = nullptr;
}
}
Json::Value executeQuery(const string& query) {
lock_guard<mutex> lock(db_mutex);
ensureConnection();
Json::Value result(Json::arrayValue);
if (mysql_query(connection, query.c_str())) {
throw runtime_error("Query failed: " + string(mysql_error(connection)));
}
MYSQL_RES* mysql_result = mysql_store_result(connection);
if (!mysql_result) return result;
MYSQL_ROW row;
MYSQL_FIELD* fields = mysql_fetch_fields(mysql_result);
int num_fields = mysql_num_fields(mysql_result);
while ((row = mysql_fetch_row(mysql_result))) {
Json::Value json_row;
for (int i = 0; i < num_fields; i++) {
const char* field_name = fields[i].name;
const char* value = row[i] ? row[i] : "";
json_row[field_name] = value;
}
result.append(json_row);
}
mysql_free_result(mysql_result);
return result;
}
bool executeUpdate(const string& query) {
lock_guard<mutex> lock(db_mutex);
ensureConnection();
return mysql_query(connection, query.c_str()) == 0;
}
int getLastInsertId() {
lock_guard<mutex> lock(db_mutex);
return mysql_insert_id(connection);
}
};
web::json::value jsonToWebJson(const Json::Value& jsoncpp_value) {
if (jsoncpp_value.isNull()) {
return web::json::value::null();
} else if (jsoncpp_value.isBool()) {
return web::json::value::boolean(jsoncpp_value.asBool());
} else if (jsoncpp_value.isInt()) {
return web::json::value::number(jsoncpp_value.asInt());
} else if (jsoncpp_value.isUInt()) {
return web::json::value::number(jsoncpp_value.asUInt());
} else if (jsoncpp_value.isDouble()) {
return web::json::value::number(jsoncpp_value.asDouble());
} else if (jsoncpp_value.isString()) {
return web::json::value::string(utility::conversions::to_string_t(jsoncpp_value.asString()));
} else if (jsoncpp_value.isArray()) {
web::json::value arr = web::json::value::array();
for (int i = 0; i < jsoncpp_value.size(); i++) {
arr[i] = jsonToWebJson(jsoncpp_value[i]);
}
return arr;
} else if (jsoncpp_value.isObject()) {
web::json::value obj = web::json::value::object();
for (const auto& key : jsoncpp_value.getMemberNames()) {
obj[utility::conversions::to_string_t(key)] = jsonToWebJson(jsoncpp_value[key]);
}
return obj;
} else {
return web::json::value::null();
}
}
string formatTime(const string& time) {
if (time.empty()) return "";
try {
int hours = stoi(time.substr(0, 2));
int minutes = stoi(time.substr(3, 2));
string period = (hours >= 12) ? "PM" : "AM";
if (hours > 12) hours -= 12;
if (hours == 0) hours = 12;
return to_string(hours) + ":" +
(minutes < 10 ? "0" : "") + to_string(minutes) + " " + period;
} catch (...) {
return time;
}
}
// School Management System
class SchoolManagementSystem {
private:
DatabaseManager db;
Graph student_course_graph;
IntervalTree schedule_tree;
void loadStudentCourseGraph() {
student_course_graph = Graph();
Json::Value enrollments = db.executeQuery(
"SELECT student_id, course_id FROM enrollments"
);
for (const auto& enrollment : enrollments) {
int student_id = stoi(enrollment["student_id"].asString());
int course_id = stoi(enrollment["course_id"].asString());
student_course_graph.addEdge(student_id, course_id);
}
}
void loadScheduleTree() {
Json::Value schedules = db.executeQuery(
"SELECT s.schedule_id, t.start_time, t.end_time, t.day_of_week, "
"c.course_name FROM schedules s "
"JOIN time_slots t ON s.slot_id = t.slot_id "
"JOIN courses c ON s.course_id = c.course_id"
);
for (const auto& schedule : schedules) {
int start = timeToMinutes(schedule["start_time"].asString());
int end = timeToMinutes(schedule["end_time"].asString());
int id = stoi(schedule["schedule_id"].asString());
string data = schedule["course_name"].asString();
schedule_tree.insert(Interval(start, end, id, data));
}
}
int timeToMinutes(const string& time) {
int hours, minutes;
char colon;
stringstream ss(time);
ss >> hours >> colon >> minutes;
return hours * 60 + minutes;
}
string getCurrentSemester() {
time_t now = time(0);
tm* ltm = localtime(&now);
int month = 1 + ltm->tm_mon;
int year = 1900 + ltm->tm_year;
// Debug output
cerr << "Current month: " << month << ", year: " << year << endl;
if (month >= 1 && month <= 4) return "Spring " + to_string(year);
if (month >= 5 && month <= 7) return "Summer " + to_string(year);
return "Fall " + to_string(year);
}
public:
SchoolManagementSystem() {
try {
loadStudentCourseGraph();
loadScheduleTree();
} catch (const exception& e) {
cerr << "Error loading graph/schedule: " << e.what() << endl;
}
}
void reloadData() {
try {
loadStudentCourseGraph();
loadScheduleTree();
} catch (const exception& e) {
cerr << "Error reloading data: " << e.what() << endl;
}
}
Json::Value getEnrollmentDetails(int enrollment_id) {
return db.executeQuery(
"SELECT e.enrollment_id, s.name AS student_name, c.course_name, "
"e.enrollment_date, e.status, e.grade "
"FROM enrollments e "
"JOIN students s ON e.student_id = s.student_id "
"JOIN courses c ON e.course_id = c.course_id "
"WHERE e.enrollment_id = " + to_string(enrollment_id)
);
}
// Fixed getTeacherAnalytics function
Json::Value SchoolManagementSystem::getTeacherAnalytics() {
Json::Value analytics(Json::objectValue);
string current_semester = getCurrentSemester();
size_t space_pos = current_semester.find(' ');
if (space_pos == string::npos) {
analytics["error"] = "Invalid semester format";
return analytics;
}
string semester_name = current_semester.substr(0, space_pos);
string semester_year = current_semester.substr(space_pos + 1);
try {
// Teacher workload query
string workload_query =
"SELECT t.teacher_id, t.name AS teacher_name, "
"COUNT(DISTINCT s.course_id) AS course_count "
"FROM teachers t "
"LEFT JOIN schedules s ON t.teacher_id = s.teacher_id "
"WHERE s.semester = '" + semester_name + "' AND s.year = '" + semester_year + "' "
"GROUP BY t.teacher_id, t.name";
Json::Value workload = db.executeQuery(workload_query);
analytics["workload"] = workload;
// Teacher effectiveness query
string effectiveness_query =
"SELECT t.name AS teacher_name, c.course_name, "
"ROUND(AVG(e.grade), 1) AS avg_grade, "
"COUNT(e.enrollment_id) AS enrollment_count, "
"ROUND(SUM(CASE WHEN e.grade >= 60 THEN 1 ELSE 0 END) / COUNT(e.enrollment_id) * 100, 1) AS pass_rate "
"FROM teachers t "
"JOIN schedules s ON t.teacher_id = s.teacher_id "
"JOIN enrollments e ON s.course_id = e.course_id "
"JOIN courses c ON s.course_id = c.course_id "
"WHERE s.semester = '" + semester_name + "' AND s.year = '" + semester_year + "' "
"AND e.grade IS NOT NULL "
"GROUP BY t.teacher_id, c.course_id";
Json::Value effectiveness = db.executeQuery(effectiveness_query);
analytics["effectiveness"] = effectiveness;
if (workload.empty() && effectiveness.empty()) {
analytics["message"] = "No teaching activity found for " + current_semester;
}
} catch (const exception& e) {
analytics["error"] = e.what();
}
return analytics;
}
// Fixed getCourseAnalytics function
Json::Value SchoolManagementSystem::getCourseAnalytics() {
Json::Value analytics(Json::objectValue);
try {
// Enrollment counts with course names
string enrollment_query =
"SELECT c.course_id, c.course_name, "
"COUNT(e.enrollment_id) AS student_count "
"FROM courses c "
"LEFT JOIN enrollments e ON c.course_id = e.course_id AND e.status = 'enrolled' "
"GROUP BY c.course_id, c.course_name";
Json::Value enrollmentCounts = db.executeQuery(enrollment_query);
analytics["students_per_course"] = enrollmentCounts;
// Find most popular course
int max_count = 0;
string popular_course_name = "No Data";
if (!enrollmentCounts.empty()) {
for (const auto& course : enrollmentCounts) {
int count = 0;
if (!course["student_count"].isNull()) {
try {
count = stoi(course["student_count"].asString());
} catch (...) {
count = 0;
}
}
if (count > max_count) {
max_count = count;
popular_course_name = course["course_name"].asString();
}
}
}
analytics["most_popular_course_name"] = popular_course_name;
analytics["most_popular_count"] = max_count;
// Fixed grade analytics with proper handling
string grade_query =
"SELECT c.course_name, "
"ROUND(AVG(e.grade), 1) as avg_grade "
"FROM enrollments e "
"JOIN courses c ON e.course_id = c.course_id "
"WHERE e.grade IS NOT NULL AND e.grade > 0 "
"GROUP BY c.course_name";
Json::Value grade_analytics = db.executeQuery(grade_query);
analytics["average_grades"] = grade_analytics;
} catch (const exception& e) {
analytics["error"] = e.what();
}
return analytics;
}
// Fix getCourseAnalytics function
// Add new endpoints to backend
Json::Value getEnrollmentCount() {
Json::Value result = db.executeQuery(
"SELECT COUNT(*) as count FROM enrollments"
);
return result[0]; // Return first row with count
}
Json::Value getRecentEnrollments() {
return db.executeQuery(
"SELECT s.name AS student_name, c.course_name, e.enrollment_date, e.status "
"FROM enrollments e "
"JOIN students s ON e.student_id = s.student_id "
"JOIN courses c ON e.course_id = c.course_id "
"ORDER BY e.enrollment_date DESC LIMIT 5"
);
}
// API Endpoints
Json::Value getStudents() {
return db.executeQuery("SELECT * FROM students");
}
Json::Value getCourses() {
return db.executeQuery(
"SELECT c.*, d.name AS department_name "
"FROM courses c "
"JOIN departments d ON c.department_id = d.department_id"
);
}
Json::Value getSchedule() {
string current_semester = getCurrentSemester();
size_t space_pos = current_semester.find(' ');
if (space_pos == string::npos) {
cerr << "Invalid semester format: " << current_semester << endl;
return Json::Value(Json::arrayValue);
}
string semester_name = current_semester.substr(0, space_pos);
string semester_year = current_semester.substr(space_pos + 1);
try {
string query =
"SELECT s.schedule_id, c.course_name, t.name as teacher_name, "
"r.room_number, "
"LOWER(SUBSTRING(ts.day_of_week, 1, 3)) as day_of_week_short, "
"ts.day_of_week, " // Add full day name
"ts.start_time, ts.end_time "
"FROM schedules s "
"JOIN courses c ON s.course_id = c.course_id "
"JOIN teachers t ON s.teacher_id = t.teacher_id "
"JOIN classrooms r ON s.room_id = r.room_id "
"JOIN time_slots ts ON s.slot_id = ts.slot_id "
"WHERE s.semester = '" + semester_name + "' AND s.year = '" + semester_year + "' "
"ORDER BY ts.day_of_week, ts.start_time";
cerr << "Executing schedule query: " << query << endl;
return db.executeQuery(query);
} catch (const exception& e) {
cerr << "Error in getSchedule: " << e.what() << endl;
return Json::Value(Json::arrayValue);
}
}
Json::Value getTeachers() {
return db.executeQuery("SELECT * FROM teachers");
}
Json::Value getEnrollments() {
return db.executeQuery(
"SELECT e.enrollment_id, e.student_id, s.name as student_name, "
"e.course_id, c.course_name, e.enrollment_date, e.status, e.grade "
"FROM enrollments e "
"JOIN students s ON e.student_id = s.student_id "
"JOIN courses c ON e.course_id = c.course_id"
);
}
Json::Value getStudentCourses(int student_id) {
string query =
"SELECT c.*, d.name AS department_name "
"FROM courses c "
"JOIN departments d ON c.department_id = d.department_id "
"JOIN enrollments e ON c.course_id = e.course_id "
"WHERE e.student_id = " + to_string(student_id) +
" AND e.status = 'enrolled'";
return db.executeQuery(query);
}
Json::Value getStudentCourseEdges() {
Json::Value edges(Json::arrayValue);
for (const auto& pair : student_course_graph.getAdjList()) {
int student_id = pair.first;
for (int course_id : pair.second) {
Json::Value edge;
edge["student_id"] = student_id;
edge["course_id"] = course_id;
edges.append(edge);
}
}
return edges;
}
Json::Value findStudentPath(int start_student, int end_student) {
Json::Value result(Json::arrayValue);
vector<int> path = student_course_graph.findPath(start_student, end_student);
for (int sid : path) result.append(sid);
return result;
}
Json::Value getCurrentEnrollments() {
return db.executeQuery(
"SELECT e.enrollment_id, s.name AS student_name, c.course_name, "
"e.enrollment_date, e.status, e.grade "
"FROM enrollments e "
"JOIN students s ON e.student_id = s.student_id "
"JOIN courses c ON e.course_id = c.course_id "
"WHERE e.status = 'enrolled'" // Only show active enrollments
);
}
bool enrollStudent(int student_id, int course_id) {
string prereq_query = "SELECT COUNT(*) as missing FROM prerequisites p "
"WHERE p.course_id = " + to_string(course_id) +
" AND p.prerequisite_course_id NOT IN ("
"SELECT e.course_id FROM enrollments e "
"WHERE e.student_id = " + to_string(student_id) +
" AND e.status = 'completed')";
Json::Value prereq_result = db.executeQuery(prereq_query);
if (!prereq_result.empty() && stoi(prereq_result[0]["missing"].asString()) > 0) {
return false;
}
string capacity_query =
"SELECT c.max_capacity, COUNT(e.enrollment_id) as enrolled "
"FROM courses c LEFT JOIN enrollments e ON c.course_id = e.course_id "
"AND e.status = 'enrolled' "
"WHERE c.course_id = " + to_string(course_id) + " "
"GROUP BY c.course_id";
Json::Value capacity_result = db.executeQuery(capacity_query);
if (!capacity_result.empty()) {
int max_cap = stoi(capacity_result[0]["max_capacity"].asString());
int enrolled = stoi(capacity_result[0]["enrolled"].asString());
if (enrolled >= max_cap) {
return false;
}
}
string enroll_query = "INSERT INTO enrollments (student_id, course_id, status) VALUES (" +
to_string(student_id) + ", " + to_string(course_id) + ", 'enrolled')";
bool success = db.executeUpdate(enroll_query);
if (success) {
student_course_graph.addEdge(student_id, course_id);
}
return success;
}
bool checkScheduleConflict(int start_time, int end_time) {
Interval new_interval(start_time, end_time, -1, "");
return schedule_tree.hasConflict(new_interval);
}
DatabaseManager& getDb() { return db; }
};
// HTTP Server
class HTTPServer {
private:
mutex sms_mutex;
SchoolManagementSystem sms;
http_listener listener;
void handleGet(http_request request) {
lock_guard<mutex> lock(sms_mutex);
auto path = request.relative_uri().path();
string path_str = utility::conversions::to_utf8string(path);
cout << "📝 Incoming GET: " << path_str << endl;
http_response response(status_codes::OK);
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Content-Type"), U("application/json"));
response.headers().add(U("Access-Control-Allow-Methods"), U("GET, POST, OPTIONS"));
response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
try {
Json::Value result;
if (path_str == "/students") {
result = sms.getStudents();
}else if (path_str == "/current-enrollments") {
result = sms.getCurrentEnrollments();
}else if (path_str.find("/enrollment-details/") == 0){
size_t pos = path_str.find_last_of('/');
if (pos != string::npos) {
string id_str = path_str.substr(pos + 1);
try {
int enrollment_id = stoi(id_str);
result = sms.getEnrollmentDetails(enrollment_id);
} catch (...) {
result["error"] = "Invalid enrollment ID";
}
}
}
else if (path_str == "/enrollment-count") {
result = sms.getEnrollmentCount();
} else if (path_str == "/recent-enrollments") {
result = sms.getRecentEnrollments();
}else if (path_str == "/courses") {
result = sms.getCourses();
} else if (path_str == "/schedule") {
result = sms.getSchedule();
} else if (path_str == "/student-course-edges") {
result = sms.getStudentCourseEdges();
} else if (path_str == "/course-analytics") {
result = sms.getCourseAnalytics();
} else if (path_str == "/teacher-analytics") {
result = sms.getTeacherAnalytics();
}
else if (path_str == "/teachers") {
result = sms.getTeachers();
}
else if (path_str == "/enrollments") {
result = sms.getEnrollments();
}
else if (path_str == "/find-student-path") {
auto query = uri::split_query(request.relative_uri().query());
int start_student = 0, end_student = 0;
if (query.find(U("start_student")) != query.end()) {
start_student = stoi(utility::conversions::to_utf8string(query[U("start_student")]));
}
if (query.find(U("end_student")) != query.end()) {
end_student = stoi(utility::conversions::to_utf8string(query[U("end_student")]));
}
Json::Value path = sms.findStudentPath(start_student, end_student);
Json::Value jsonResult;
for (auto sid : path) {
jsonResult.append(sid);
}
result = jsonResult;
} else {
response.set_status_code(status_codes::NotFound);
result["error"] = "Endpoint not found";
}
response.set_body(jsonToWebJson(result));
} catch (const exception& e) {
response.set_status_code(status_codes::InternalError);
web::json::value error = web::json::value::object();
error[U("error")] = web::json::value::string(
utility::conversions::to_string_t(e.what()));
response.set_body(error);
}
request.reply(response);
}
void handlePost(http_request request) {
lock_guard<mutex> lock(sms_mutex);
request.extract_json().then([=](pplx::task<web::json::value> task) {
try {
auto json_data = task.get();
auto path = request.relative_uri().path();
string path_str = utility::conversions::to_utf8string(path);
http_response response(status_codes::OK);
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Content-Type"), U("application/json"));
response.headers().add(U("Access-Control-Allow-Methods"), U("GET, POST, OPTIONS"));
response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
web::json::value result = web::json::value::object();
if (path_str == "/add-student") {
string name = utility::conversions::to_utf8string(
json_data[U("name")].as_string());
string email = utility::conversions::to_utf8string(
json_data[U("email")].as_string());
string phone = json_data.has_field(U("phone")) ?
utility::conversions::to_utf8string(
json_data[U("phone")].as_string()) : "";
string address = json_data.has_field(U("address")) ?
utility::conversions::to_utf8string(
json_data[U("address")].as_string()) : "";
string insert_query =
"INSERT INTO students (name, email, phone, address, status, enrollment_date) "
"VALUES ('" + name + "', '" + email + "', '" +
phone + "', '" + address + "', 'active', CURDATE())";
bool success = sms.getDb().executeUpdate(insert_query);
result[U("success")] = web::json::value::boolean(success);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
success ? "Student added successfully" : "Failed to add student"
)
);
} else if (path_str.find("/enrollment-details/") == 0) {
size_t pos = path_str.find_last_of('/');
if (pos != string::npos) {
string id_str = path_str.substr(pos + 1);
try {
int enrollment_id = stoi(id_str);
result = jsonToWebJson(sms.getEnrollmentDetails(enrollment_id));
} catch (...) {
result[U("error")] = web::json::value::string(U("Invalid enrollment ID"));
}
}
}
else if (path_str == "/add-course") {
string course_code = utility::conversions::to_utf8string(
json_data[U("course_code")].as_string());
string course_name = utility::conversions::to_utf8string(
json_data[U("course_name")].as_string());
string department_name = utility::conversions::to_utf8string(
json_data[U("department")].as_string());
int credits = json_data[U("credits")].as_integer();
int max_capacity = json_data[U("max_capacity")].as_integer();
string description = json_data.has_field(U("description")) ?
utility::conversions::to_utf8string(
json_data[U("description")].as_string()) : "";
string dept_query = "SELECT department_id FROM departments WHERE name = '" +
department_name + "'";
Json::Value dept_result = sms.getDb().executeQuery(dept_query);
int department_id = -1;
if (dept_result.empty()) {
string insert_dept = "INSERT INTO departments (name) VALUES ('" +
department_name + "')";
if (!sms.getDb().executeUpdate(insert_dept)) {
throw runtime_error("Failed to create department");
}
department_id = sms.getDb().getLastInsertId();
} else {
department_id = stoi(dept_result[0]["department_id"].asString());
}
string insert_query =
"INSERT INTO courses (course_code, course_name, credits, department_id, max_capacity, description) "
"VALUES ('" + course_code + "', '" + course_name + "', " +
to_string(credits) + ", " + to_string(department_id) + ", " +
to_string(max_capacity) + ", '" + description + "')";
bool success = sms.getDb().executeUpdate(insert_query);
int course_id = sms.getDb().getLastInsertId();
if (json_data.has_field(U("prerequisites"))) {
auto prerequisites = json_data[U("prerequisites")].as_array();
for (const auto& prereq : prerequisites) {
int prereq_id = prereq.as_integer();
string prereq_query =
"INSERT INTO prerequisites (course_id, prerequisite_course_id) "
"VALUES (" + to_string(course_id) + ", " + to_string(prereq_id) + ")";
sms.getDb().executeUpdate(prereq_query);
}
}
result[U("success")] = web::json::value::boolean(success);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
success ? "Course added successfully" : "Failed to add course"
)
);
} else if (path_str == "/enroll") {
int student_id = json_data[U("student_id")].as_integer();
int course_id = json_data[U("course_id")].as_integer();
string prereq_query =
"SELECT COUNT(*) as missing FROM prerequisites p "
"WHERE p.course_id = " + to_string(course_id) +
" AND p.prerequisite_course_id NOT IN ("
"SELECT e.course_id FROM enrollments e "
"WHERE e.student_id = " + to_string(student_id) +
" AND e.status = 'completed'"
")";
Json::Value prereq_result = sms.getDb().executeQuery(prereq_query);
if (!prereq_result.empty() && stoi(prereq_result[0]["missing"].asString()) > 0) {
result[U("success")] = web::json::value::boolean(false);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
"Student is missing prerequisites for this course."
)
);
response.set_body(result);
request.reply(response);
return;
}
string capacity_query =
"SELECT c.max_capacity, COUNT(e.enrollment_id) as enrolled "
"FROM courses c LEFT JOIN enrollments e ON c.course_id = e.course_id "
"AND e.status = 'enrolled' "
"WHERE c.course_id = " + to_string(course_id) + " "
"GROUP BY c.course_id";
Json::Value capacity_result = sms.getDb().executeQuery(capacity_query);
if (!capacity_result.empty()) {
int max_cap = stoi(capacity_result[0]["max_capacity"].asString());
int enrolled = stoi(capacity_result[0]["enrolled"].asString());
if (enrolled >= max_cap) {
result[U("success")] = web::json::value::boolean(false);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t("Course is already full.")
);
response.set_body(result);
request.reply(response);
return;
}
}
string already_query =
"SELECT COUNT(*) as cnt FROM enrollments WHERE student_id = " +
to_string(student_id) +
" AND course_id = " + to_string(course_id) + " AND status = 'enrolled'";
Json::Value already_result = sms.getDb().executeQuery(already_query);
if (!already_result.empty() && stoi(already_result[0]["cnt"].asString()) > 0) {
result[U("success")] = web::json::value::boolean(false);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t("Student is already enrolled in this course.")
);
response.set_body(result);
request.reply(response);
return;
}
bool enroll_success = sms.enrollStudent(student_id, course_id);
result[U("success")] = web::json::value::boolean(enroll_success);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
enroll_success ? "Enrollment successful" :
"Enrollment failed due to a database error."
)
);
} else if (path_str == "/find-student-path") {
int start_id = json_data[U("start_student")].as_integer();
int end_id = json_data[U("end_student")].as_integer();
Json::Value path = sms.findStudentPath(start_id, end_id);
result = jsonToWebJson(path);
response.set_body(result);
request.reply(response);
return;
} else if (path_str == "/check-schedule-conflict") {
string start_time = utility::conversions::to_utf8string(
json_data[U("start_time")].as_string());
string end_time = utility::conversions::to_utf8string(
json_data[U("end_time")].as_string());
int start_minutes = timeToMinutes(start_time);
int end_minutes = timeToMinutes(end_time);
bool has_conflict = sms.checkScheduleConflict(start_minutes, end_minutes);
result[U("has_conflict")] = web::json::value::boolean(has_conflict);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
has_conflict ? "Schedule conflict detected" : "No schedule conflict"
)
);
} else if (path_str == "/student-courses") {
int student_id = json_data[U("student_id")].as_integer();
Json::Value courses = sms.getStudentCourses(student_id);
result = jsonToWebJson(courses);
response.set_body(result);
request.reply(response);
return;
} else if (path_str == "/reload-data") {
sms.reloadData();
result[U("success")] = web::json::value::boolean(true);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t("Data reloaded successfully")
);
} else if (path_str == "/update-grade") {
int student_id = json_data[U("student_id")].as_integer();
int course_id = json_data[U("course_id")].as_integer();
double grade = json_data[U("grade")].as_double();
string update_query =
"UPDATE enrollments SET grade = " + to_string(grade) +
" WHERE student_id = " + to_string(student_id) +
" AND course_id = " + to_string(course_id);
bool success = sms.getDb().executeUpdate(update_query);
result[U("success")] = web::json::value::boolean(success);
result[U("message")] = web::json::value::string(
utility::conversions::to_string_t(
success ? "Grade updated successfully" : "Failed to update grade"
)