-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_backup.cpp
More file actions
717 lines (607 loc) · 26.6 KB
/
Copy pathmain_backup.cpp
File metadata and controls
717 lines (607 loc) · 26.6 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
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <mysql/mysql.h>
#include <json/json.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
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) {
return adj_list[student_id];
}
vector<int> getCourseStudents(int course_id) {
vector<int> students;
for (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();
// Get courses for current student
vector<int> courses = getStudentCourses(current);
// For each course, find other students
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) {
// Reconstruct path
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 {}; // No path found
}
const std::map<int, std::vector<int>>& getAdjList() const { return adj_list; }
};
// Greedy Scheduler
class GreedyScheduler {
private:
struct Activity {
int start, end, id;
string name;
Activity(int s, int e, int i, string n) : start(s), end(e), id(i), name(n) {}
};
static bool compareByEnd(const Activity& a, const Activity& b) {
return a.end < b.end;
}
public:
vector<int> scheduleActivities(vector<Activity>& activities) {
sort(activities.begin(), activities.end(), compareByEnd);
vector<int> result;
if (activities.empty()) return result;
result.push_back(0);
int last_selected = 0;
for (int i = 1; i < activities.size(); i++) {
if (activities[i].start >= activities[last_selected].end) {
result.push_back(i);
last_selected = i;
}
}
return result;
}
};
// Database Manager
class DatabaseManager {
private:
public:
DatabaseManager() {
MYSQL* connection = mysql_init(nullptr);
connection = mysql_init(0);
if (!connection) {
throw runtime_error("MySQL initialization failed");
}
if (!mysql_real_connect(connection, "localhost", "root", "password", "school_management2", 0, NULL, 0)) {
std::string error_msg = connection ? mysql_error(connection) : "No connection object";
throw std::runtime_error("Database connection failed: " + error_msg);
}
}
~DatabaseManager() {
MYSQL* connection = mysql_init(nullptr);
if (connection) {
mysql_close(connection);
}
}
Json::Value executeQuery(const string& query) {
MYSQL* connection = mysql_init(nullptr);
Json::Value result(Json::arrayValue);
if (!connection || mysql_ping(connection)) {
std::cerr << "🔄 Reconnecting to MySQL...\n";
connection = mysql_real_connect(connection, "localhost", "root", "jazz45@10#man","school_management", 0, NULL, 0);
if (!connection) {
throw std::runtime_error("Reconnection failed: " + std::string(mysql_error(connection)));
}
}
if (!connection) {
throw std::runtime_error("No active DB connection");
}
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);
std::cout << "🧮 Fields: " << num_fields << std::endl;
for (int i = 0; i < num_fields; i++) {
std::cout << " - " << (fields[i].name ? fields[i].name : "NULL") << std::endl;
}
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 ? fields[i].name : "unknown";
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) {
MYSQL* connection = mysql_init(nullptr);
if (!connection || mysql_ping(connection)) {
std::cerr << "🔄 Reconnecting to MySQL...\n";
connection = mysql_real_connect(connection, "localhost", "root", "jazz45@10#man","school_management", 0, NULL, 0);
if (!connection) {
throw std::runtime_error("Reconnection failed: " + std::string(mysql_error(connection)));
}
}
if (!connection) {
std::cerr << "❌ No active connection for update." << std::endl;
return false;
}
return mysql_query(connection, query.c_str()) == 0;
}
};
// Helper function to convert Json::Value to web::json::value
web::json::value jsonToWebJson(const Json::Value& jsoncpp_value) {
web::json::value web_json;
if (jsoncpp_value.isArray()) {
web_json = web::json::value::array();
for (int i = 0; i < jsoncpp_value.size(); i++) {
web_json[i] = jsonToWebJson(jsoncpp_value[i]);
}
} else if (jsoncpp_value.isObject()) {
web_json = web::json::value::object();
for (const auto& key : jsoncpp_value.getMemberNames()) {
web_json[utility::conversions::to_string_t(key)] = jsonToWebJson(jsoncpp_value[key]);
}
} else if (jsoncpp_value.isString()) {
web_json = web::json::value::string(utility::conversions::to_string_t(jsoncpp_value.asString()));
} else if (jsoncpp_value.isInt()) {
web_json = web::json::value::number(jsoncpp_value.asInt());
} else if (jsoncpp_value.isDouble()) {
web_json = web::json::value::number(jsoncpp_value.asDouble());
} else if (jsoncpp_value.isBool()) {
web_json = web::json::value::boolean(jsoncpp_value.asBool());
} else {
web_json = web::json::value::null();
}
return web_json;
}
// School Management System
class SchoolManagementSystem {
private:
DatabaseManager db;
Graph student_course_graph;
IntervalTree schedule_tree;
public:
SchoolManagementSystem() {
loadStudentCourseGraph();
loadScheduleTree();
}
void loadStudentCourseGraph() {
// Clear the graph before reloading
student_course_graph = Graph();
Json::Value enrollments = db.executeQuery(
"SELECT student_id, course_id FROM enrollments WHERE status = 'enrolled'"
);
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 = stoi(time.substr(0, 2));
int minutes = stoi(time.substr(3, 2));
return hours * 60 + minutes;
}
// API Endpoints
Json::Value getStudents() {
try {
std::cout << "🔍 Executing SELECT query...\n";
return db.executeQuery("SELECT * FROM students");
} catch (const std::exception& e) {
std::cerr << "💥 getStudents error: " << e.what() << "\n";
return Json::Value(Json::arrayValue); // return empty
}
}
Json::Value getCourses() {
return db.executeQuery("SELECT * FROM courses");
}
Json::Value getSchedule() {
return db.executeQuery(
"SELECT s.schedule_id, c.course_name, t.name as teacher_name, "
"r.room_number, ts.day_of_week, 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 "
"ORDER BY ts.day_of_week, ts.start_time"
);
}
Json::Value getStudentCourses(int student_id) {
string query = "SELECT c.* FROM courses c "
"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 getCourseStudents(int course_id) {
string query = "SELECT s.* FROM students s "
"JOIN enrollments e ON s.student_id = e.student_id "
"WHERE e.course_id = " + to_string(course_id) +
" AND e.status = 'enrolled'";
return db.executeQuery(query);
}
bool enrollStudent(int student_id, int course_id) {
// Check prerequisites
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 (stoi(prereq_result[0]["missing"].asString()) > 0) {
return false; // Missing prerequisites
}
// Check capacity
string capacity_query = "SELECT c.max_capacity, COUNT(e.student_id) as enrolled "
"FROM courses c LEFT JOIN enrollments e ON c.course_id = e.course_id "
"WHERE c.course_id = " + to_string(course_id) +
" AND (e.status = 'enrolled' OR e.status IS NULL) "
"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; // Course full
}
}
// Enroll student
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) {
// Reload the graph to ensure consistency
loadStudentCourseGraph();
}
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; }
public:
// Returns all student-course edges
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;
}
// Returns shortest path (student IDs) between two students
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;
}
// Returns analytics: students per course, most popular course, etc.
Json::Value getCourseAnalytics() {
Json::Value analytics(Json::objectValue);
map<int, int> course_counts;
int max_count = 0, popular_course = -1;
for (const auto& pair : student_course_graph.getAdjList()) {
for (int course_id : pair.second) {
course_counts[course_id]++;
if (course_counts[course_id] > max_count) {
max_count = course_counts[course_id];
popular_course = course_id;
}
}
}
Json::Value per_course(Json::arrayValue);
for (const auto& p : course_counts) {
Json::Value entry;
entry["course_id"] = p.first;
entry["student_count"] = p.second;
per_course.append(entry);
}
analytics["students_per_course"] = per_course;
analytics["most_popular_course_id"] = popular_course;
analytics["most_popular_count"] = max_count;
return analytics;
}
};
// HTTP Server
class HTTPServer {
private:
SchoolManagementSystem sms;
http_listener listener;
public:
HTTPServer(const string& address) : listener(http::uri(utility::conversions::to_string_t(address))) {
listener.support(methods::GET, [this](http_request request) {
handleGet(request);
});
listener.support(methods::POST, [this](http_request request) {
handlePost(request);
});
listener.support(methods::OPTIONS, [this](http_request request) {
http_response response(status_codes::OK);
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Access-Control-Allow-Methods"), U("GET, POST, OPTIONS"));
response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
request.reply(response);
});
}
void handleGet(http_request request) {
auto path = request.relative_uri().path();
std::string path_str = utility::conversions::to_utf8string(path);
std::cout << "📥 Incoming GET: " << path_str << std::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"));
try {
Json::Value result;
string path_str = utility::conversions::to_utf8string(path);
if (path_str == "/students") {
std::cout << "✅ Calling getStudents()\n";
result = sms.getStudents();
} 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 {
response.set_status_code(status_codes::NotFound);
result["error"] = "Endpoint not found";
}
web::json::value web_result = jsonToWebJson(result);
response.set_body(web_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) {
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"));
web::json::value result = web::json::value::object();
bool success = false;
if (path_str == "/enroll") {
int student_id = json_data[U("student_id")].as_integer();
int course_id = json_data[U("course_id")].as_integer();
// Check prerequisites
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;
}
// Check capacity
string capacity_query =
"SELECT c.max_capacity, COUNT(e.student_id) as enrolled "
"FROM courses c LEFT JOIN enrollments e ON c.course_id = e.course_id "
"WHERE c.course_id = " + to_string(course_id) +
" AND (e.status = 'enrolled' OR e.status IS NULL) "
"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;
}
}
// Check if already enrolled
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;
}
// Enroll student
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."
)
);
response.set_body(result);
request.reply(response);
return;
} 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);
web::json::value web_result = jsonToWebJson(path);
response.set_body(web_result);
request.reply(response);
return;
} else {
response.set_status_code(status_codes::NotFound);
result[U("error")] = web::json::value::string(U("Endpoint not found"));
}
response.set_body(result);
request.reply(response);
} catch (const exception& e) {
http_response response(status_codes::InternalError);
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Content-Type"), U("application/json"));
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);
}
});
}
pplx::task<void> start() {
return listener.open();
}
pplx::task<void> stop() {
return listener.close();
}
};
int main() {
try {
HTTPServer server("http://localhost:8080");
cout << "Starting School Management System server on http://localhost:8080" << endl;
server.start().wait();
cout << "Press Enter to exit..." << endl;
string line;
getline(cin, line);
server.stop().wait();
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
return 1;
}
return 0;
}