-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_context.txt
More file actions
9634 lines (8790 loc) · 381 KB
/
Copy pathcode_context.txt
File metadata and controls
9634 lines (8790 loc) · 381 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
// File: backend/database.js
const mysql = require('mysql2/promise');
const dotenv = require('dotenv');
dotenv.config();
const dbName = 'healthconsultant'; // Your database name
let pool; // Use a connection pool for efficiency
async function connectToDatabase() {
try {
pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost', // Replace with your MySQL host
user: process.env.DB_USER || 'root', // Replace with your MySQL user
password: process.env.DB_PASSWORD || '', // Replace with your MySQL password,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Test the connection and create the database if it doesn't exist
const connection = await pool.getConnection();
try {
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${dbName}\`;`);
console.log(`Database "${dbName}" created (if it didn't exist).`);
} finally {
connection.release();
}
// Now, switch the connection pool to use the created database
pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost', // Replace with your MySQL host
user: process.env.DB_USER || 'root', // Replace with your MySQL user
password: process.env.DB_PASSWORD || '', // Replace with your MySQL password
database: process.env.DB_NAME || dbName,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
const newConnection = await pool.getConnection();
console.log('Connected to the database.');
newConnection.release(); // Release the connection back to the pool
return pool;
} catch (error) {
console.error('Database connection error:', error.message);
throw error;
}
}
async function initializeDatabase() {
try {
await connectToDatabase();
await createTables();
await seedConsultants();
console.log("Database initialized successfully.");
} catch (error) {
console.error("Database initialization failed:", error.message);
throw error;
}
}
async function createTables() {
try {
const connection = await pool.getConnection();
// Users Table
await connection.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
fullName VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role VARCHAR(50) DEFAULT 'user',
phone VARCHAR(20) NOT NULL,
profilePicture VARCHAR(255) DEFAULT NULL,
bloodGroup VARCHAR(10) DEFAULT NULL,
medicalHistory TEXT DEFAULT NULL,
currentPrescriptions TEXT DEFAULT NULL,
isConsultant TINYINT DEFAULT 0,
bio TEXT DEFAULT NULL,
qualification VARCHAR(255) DEFAULT NULL,
areasOfExpertise TEXT DEFAULT NULL,
speciality VARCHAR(255) DEFAULT NULL,
availability TEXT DEFAULT NULL,
bankAccount VARCHAR(255) DEFAULT NULL,
consultingFees DECIMAL(10, 2) DEFAULT NULL,
certificates TEXT DEFAULT NULL,
isApproved TINYINT DEFAULT 0
);
`);
// Consultants Table (Consider removing - fields are now in users)
await connection.query(`
CREATE TABLE IF NOT EXISTS consultants (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT,
specialty VARCHAR(255),
qualifications TEXT,
availability TEXT,
imageUrl VARCHAR(255),
FOREIGN KEY (userId) REFERENCES users(id)
);
`);
// Bookings Table
await connection.query(`
CREATE TABLE IF NOT EXISTS bookings (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT,
consultantId INT,
date DATE,
time TIME,
status VARCHAR(50),
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (consultantId) REFERENCES users(id)
);
`);
// Health Records Table
await connection.query(`
CREATE TABLE IF NOT EXISTS healthrecords (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT,
medicalHistory TEXT,
ongoingTreatments TEXT,
prescriptions TEXT,
FOREIGN KEY (userId) REFERENCES users(id)
);
`);
// Messages Table
await connection.query(`
CREATE TABLE IF NOT EXISTS messages (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT,
consultantId INT,
message TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (consultantId) REFERENCES users(id)
);
`);
// Chat Requests Table
await connection.query(`
CREATE TABLE IF NOT EXISTS chat_requests (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT NOT NULL,
consultantId INT NOT NULL,
bookingId INT NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (consultantId) REFERENCES users(id),
FOREIGN KEY (bookingId) REFERENCES bookings(id),
UNIQUE (userId, consultantId, bookingId)
);
`);
// Chats Table
await connection.query(`
CREATE TABLE IF NOT EXISTS chats (
id INT PRIMARY KEY AUTO_INCREMENT,
chatRequestId INT NOT NULL,
senderId INT NOT NULL,
message TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (chatRequestId) REFERENCES chat_requests(id),
FOREIGN KEY (senderId) REFERENCES users(id)
);
`);
// Reviews Table
await connection.query(`
CREATE TABLE IF NOT EXISTS reviews (
id INT PRIMARY KEY AUTO_INCREMENT,
userId INT,
consultantId INT,
rating INT,
review TEXT,
bookingId INT,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (consultantId) REFERENCES users(id),
FOREIGN KEY (bookingId) REFERENCES bookings(id)
);
`);
// Contacts Table
await connection.query(`
CREATE TABLE IF NOT EXISTS contacts (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
email VARCHAR(255),
subject VARCHAR(255),
message TEXT
);
`);
// Payments Table
await connection.query(`
CREATE TABLE IF NOT EXISTS payments (
id INT PRIMARY KEY AUTO_INCREMENT,
bookingId INT NOT NULL,
userId INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
paymentDate DATETIME NOT NULL,
paymentMethod VARCHAR(255),
status VARCHAR(50) NOT NULL,
FOREIGN KEY (bookingId) REFERENCES bookings(id),
FOREIGN KEY (userId) REFERENCES users(id)
);
`);
// Refunds Table
await connection.query(`
CREATE TABLE IF NOT EXISTS refunds (
id INT PRIMARY KEY AUTO_INCREMENT,
paymentId INT NOT NULL,
refundDate DATETIME NOT NULL,
refundAmount DECIMAL(10, 2) NOT NULL,
reason TEXT,
FOREIGN KEY (paymentId) REFERENCES payments(id)
);
`);
connection.release();
console.log('Tables created successfully.');
} catch (error) {
console.error('Error creating tables:', error.message);
throw error;
}
}
async function seedConsultants() {
try {
const connection = await pool.getConnection();
// Check if users table is empty
const [rows] = await connection.query("SELECT COUNT(*) AS count FROM users");
const count = rows[0].count;
if (count === 0) {
const users = [
{
fullName: "Dr. Jane Doe",
email: "jane.doe@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "consultant",
phone: "555-123-4567",
bio: "Experienced cardiologist",
qualification: "MD, Cardiology",
areasOfExpertise: "Heart failure, Hypertension",
speciality: "Cardiology",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "1234567890",
isApproved: 1,
profilePicture: "uploads\\doc2.avif",
consultingFees: 250.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 1,
},
{
fullName: "Dr. John Smith",
email: "john.smith@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "consultant",
phone: "555-987-6543",
bio: "Neurologist specializing in migraines",
qualification: "PhD, Neurology",
areasOfExpertise: "Migraines, Epilepsy",
speciality: "Neurology",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "0987654321",
isApproved: 0,
profilePicture: "uploads\\doc1.jpeg",
consultingFees: 300.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 1,
},
{
fullName: "Dr. Emily Chen",
email: "emily.chen@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "consultant",
phone: "555-555-5555",
bio: "Pediatrician with a passion for child health",
qualification: "MD, Pediatrics",
areasOfExpertise: "Childhood illnesses, Vaccinations",
speciality: "Pediatrics",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "1122334455",
isApproved: 1,
profilePicture: "uploads\\doc3.avif",
consultingFees: 400.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 1,
},
{
fullName: "Admin User",
email: "admin@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "admin",
phone: "9999999999",
bio: "Admin Here",
qualification: "Admin, Health Consultant",
areasOfExpertise: "Management",
speciality: "Management",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "0000000000",
isApproved: 1,
profilePicture: "uploads\\admin.png",
consultingFees: 120.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 2,
},
{
fullName: "Dr. Alice Johnson",
email: "alice.j@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "consultant",
phone: "8888888888",
bio: "Dentist with a passion for child health",
qualification: "Dentist",
areasOfExpertise: "Child Dentistry",
speciality: "Dentist",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "1212121212",
isApproved: 0,
profilePicture: "uploads\\doc4.avif",
consultingFees: 500.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 1,
},
{
fullName: "Test User",
email: "user@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "user",
phone: "7777777777",
bio: "Simple User",
qualification: "None",
areasOfExpertise: "None",
speciality: "None",
availability: null,
bankAccount: null,
isApproved: 0,
profilePicture: "uploads\\default.png",
consultingFees: null,
certificates: null,
isConsultant: 0,
},
{
fullName: "Dr. Bob Williams",
email: "bob.williams@example.com",
password: "$2b$10$O3jfFgJVuZ028Z2u.GCrk.SSpvbdzVUFc4sjI78Jzgsd.3qhyOlo.",
role: "consultant",
phone: "6666666666",
bio: "Dermatologist specializing in skin conditions",
qualification: "MD, Dermatology",
areasOfExpertise: "Acne, Eczema",
speciality: "Dermatology",
availability: JSON.stringify({"Monday": "9:00-17:00", "Tuesday": "9:00-17:00"}),
bankAccount: "3434343434",
isApproved: 1,
profilePicture: "uploads\\doc5.jpg",
consultingFees: 450.00,
certificates: JSON.stringify([{"name":"document1","path":"uploads\\document1.png"},{"name":"document2","path":"uploads\\document2.png"}]),
isConsultant: 1,
},
];
for (const user of users) {
const {
fullName,
email,
password,
role,
phone,
bio,
qualification,
areasOfExpertise,
speciality,
availability,
bankAccount,
isApproved,
profilePicture,
consultingFees,
certificates,
isConsultant,
} = user;
await connection.query(
`
INSERT INTO users (fullName, email, password, role, phone, isConsultant, bio, qualification, areasOfExpertise, speciality, availability, bankAccount, isApproved, profilePicture, consultingFees, certificates)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[
fullName,
email,
password,
role,
phone,
isConsultant,
bio,
qualification,
areasOfExpertise,
speciality,
availability,
bankAccount,
isApproved,
profilePicture,
consultingFees,
certificates,
]
);
}
// Add the reviews table data at the end of seedConsultants()
await connection.query(`
INSERT INTO reviews (userId, consultantId, rating, review, bookingId) VALUES
(6, 1, 5, 'Excellent consultation! Highly recommended.', 1),
(6, 2, 4, 'Very helpful and informative session.', 2),
(6, 1, 3, 'Good but could be better.', 3);
`);
console.log("Consultants table seeded with dummy data.");
} else {
console.log("Consultants table already has data, skipping seeding.");
}
connection.release();
} catch (error) {
console.error('Error seeding consultants:', error.message);
}
}
module.exports = {
initializeDatabase,
getDb: () => pool, // Return the connection pool
};
// File: backend/server.js
const express = require("express");
const cors = require("cors");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { body, validationResult } = require("express-validator");
const { initializeDatabase, getDb } = require("./database");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const morgan = require("morgan");
const dotenv = require("dotenv");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const { promisify } = require("util");
dotenv.config();
const app = express();
const port = process.env.PORT || 5555;
// Security Enhancements
// const limiter = rateLimit({
// windowMs: 15 * 60 * 1000, // 15 minutes
// max: 100, // Limit each IP to 100 requests per windowMs
// message: "Too many requests from this IP, please try again after 15 minutes",
// });
app.use(helmet());
// app.use(limiter);
app.use(morgan("dev"));
// CORS Configuration
app.use(
cors({
origin: (origin, callback) => {
const allowedOrigins = ["http://localhost:5173"]; // Use an environment variable for production
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
app.use(express.json());
// Multer configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(
null,
file.fieldname +
"-" +
uniqueSuffix +
"." +
file.originalname.split(".").pop()
);
},
});
const upload = multer({ storage: storage });
// Initialize database
initializeDatabase()
.then(() => {
// Helper function to handle database errors
const handleDatabaseError = (req, res, err, message) => {
console.error(req.originalUrl + ": ", err.message);
if (res && typeof res.status === "function") {
return res.status(500).json({
message: message || "Database operation failed",
error: err.message,
});
} else {
console.error("Response object is not valid:", res);
return; // Or throw an error, depending on the desired behavior
}
};
// Helper function to generate JWT token
const generateToken = (user) => {
return jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET || "secret",
{ expiresIn: "1h" }
); // Use environment variable for secret
};
// User Registration
app.post(
"/api/register",
upload.fields([
{ name: "profilePicture", maxCount: 1 },
{ name: "certificates", maxCount: 10 }, // Allow up to 10 certificates
]),
[
body("fullName").notEmpty().withMessage("Full name is required"),
body("email").isEmail().withMessage("Invalid email address"),
body("password")
.isLength({ min: 6 })
.withMessage("Password must be at least 6 characters long"),
body("role")
.isIn(["user", "consultant", "admin"]) //Removed admin role from here
.withMessage("Invalid role selected"),
body("phone").notEmpty().withMessage("Phone number is required"), //Added phone validation
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
fullName,
email,
password,
role,
phone, //Get the phone number here
bloodGroup,
medicalHistory,
currentPrescriptions,
bio, // Consultant specific
qualification, // Consultant specific
areasOfExpertise,
speciality, // Consultant specific
availability, // Consultant specific
bankAccount, // Consultant Specific
consultingFees, // Consultant Specific
} = req.body;
const profilePicture =
req.files && req.files["profilePicture"]
? req.files["profilePicture"][0].path
: null;
let certificatesData = [];
if (req.files && req.files["certificates"]) {
const certificates = Array.isArray(req.files["certificates"])
? req.files["certificates"]
: [req.files["certificates"]];
try {
const certificateNames = JSON.parse(req.body.certificateNames); // Parse certificate names from request body
certificatesData = certificates.map((file, index) => ({
name: certificateNames[index] || file.originalname, // Use provided name or original filename
path: file.path,
}));
} catch (error) {
console.error("Error parsing certificateNames:", error);
return res
.status(400)
.json({ message: "Invalid certificate names format" });
}
}
try {
const hashedPassword = await bcrypt.hash(password, 10);
const pool = getDb(); // Get the connection pool
const connection = await pool.getConnection(); // Get a connection from the pool
try {
const isConsultant = role === "consultant" ? 1 : 0; // Set isConsultant flag
// Construct the SQL query dynamically
let sql =
"INSERT INTO users (fullName, email, password, role, phone, isConsultant, profilePicture";
let values = [
fullName,
email,
hashedPassword,
role,
phone,
isConsultant,
profilePicture,
];
// Add fields based on role
if (role === "user") {
sql +=
", bloodGroup, medicalHistory, currentPrescriptions) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
values.push(bloodGroup, medicalHistory, currentPrescriptions);
} else if (role === "consultant") {
sql +=
", bio, qualification, areasOfExpertise, speciality, availability, bankAccount, consultingFees, certificates, isApproved) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
values.push(
bio,
qualification,
areasOfExpertise,
speciality,
availability,
bankAccount,
consultingFees,
JSON.stringify(certificatesData),
0
); // isApproved default 0
} else {
sql += ") VALUES (?, ?, ?, ?, ?, ?, ?)"; //role = admin
}
// Execute the SQL query
const [result] = await connection.query(sql, values);
const userId = result.insertId;
// Send successful response
res.status(201).json({
id: userId,
fullName,
email,
phone,
role,
isConsultant,
isApproved: 0,
profilePicture,
});
} finally {
connection.release(); // Release the connection back to the pool
}
} catch (error) {
console.error(error);
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ message: "Email already exists" });
}
res.status(500).json({ message: "Registration failed", error: error.message });
}
}
);
// User Login
app.post(
"/api/login",
[
body("email").isEmail().withMessage("Invalid email address"),
body("password").notEmpty().withMessage("Password is required"),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
const [rows] = await connection.query("SELECT * FROM users WHERE email = ?", [email]);
const user = rows[0];
if (!user) {
return res.status(400).json({ message: "Invalid credentials" });
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(400).json({ message: "Invalid credentials" });
}
const token = generateToken(user);
res.json({
token,
role: user.role,
userId: user.id,
isConsultant: user.isConsultant,
isApproved: user.isApproved,
profilePicture: user.profilePicture,
});
} finally {
connection.release();
}
} catch (error) {
console.error(error);
res.status(500).json({ message: "Login failed", error: error.message });
}
}
);
// Authentication Middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ message: "Authentication required" });
}
jwt.verify(token, process.env.JWT_SECRET || "secret", (err, user) => {
if (err) {
return res
.status(403)
.json({ message: "Invalid token", error: err.message });
}
req.user = user;
next();
});
};
// Endpoint to fetch consultant's documents
app.get("/api/consultant/:consultantId/documents", async (req, res) => {
const { consultantId } = req.params;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
// Fetch user by ID
const [rows] = await connection.query(
"SELECT certificates FROM users WHERE id = ? AND role = 'consultant'",
[consultantId]
);
const row = rows[0];
if (!row) {
return res
.status(404)
.json({
message: "Consultant not found or does not have documents.",
});
}
// Parse the certificates from string to array
const certificates = JSON.parse(row.certificates) || [];
res.status(200).json({ certificates });
} finally {
connection.release();
}
} catch (error) {
console.error(error);
res
.status(500)
.json({ message: "Failed to fetch consultant documents", error: error.message });
}
});
// User Payments API (GET)
app.get("/api/user/payments", authenticateToken, async (req, res) => {
const userId = req.user.userId;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
const [payments] = await connection.query(
`SELECT
p.*,
b.date AS bookingDate,
b.time AS bookingTime,
r.refundAmount AS refundAmount
FROM
payments p
INNER JOIN
bookings b ON p.bookingId = b.id
LEFT JOIN
refunds r ON p.id = r.paymentId
WHERE
p.userId = ?`,
[userId]
);
// Process payments to calculate final amount
const processedPayments = payments.map((payment) => {
let finalAmount = payment.amount;
if (payment.status === "refunded" && payment.refundAmount) {
finalAmount -= payment.refundAmount; // Make the refund amount negative
}
return {
...payment,
finalAmount: finalAmount,
};
});
res.json(processedPayments);
} finally {
connection.release();
}
} catch (error) {
console.error(error);
res.status(500).json({ message: "Failed to retrieve payments", error: error.message });
}
});
// Consultant Earnings API (GET)
app.get("/api/consultant/earnings", authenticateToken, async (req, res) => {
const userId = req.user.userId;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
const [earnings] = await connection.query(
`
SELECT p.*, b.date as bookingDate, b.time as bookingTime
FROM payments p
INNER JOIN bookings b ON p.bookingId = b.id
WHERE b.consultantId = ?
AND p.status = 'paid'
AND b.status NOT IN ('rejected', 'canceled') -- Exclude rejected and cancelled bookings
`,
[userId]
);
res.json(earnings);
} finally {
connection.release();
}
} catch (error) {
console.error(error);
res.status(500).json({ message: "Failed to retrieve earnings", error: error.message });
}
});
// User Profile (GET)
app.get("/api/profile", authenticateToken, async (req, res) => {
const userId = req.user.userId;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
const [rows] = await connection.query(`SELECT
id,
fullName,
email,
role,
phone,
profilePicture,
bloodGroup,
medicalHistory,
currentPrescriptions,
isConsultant,
bio,
qualification,
areasOfExpertise,
speciality,
availability,
bankAccount,
isApproved
FROM users WHERE id = ?`, [userId]);
const user = rows[0];
if (!user) {
return res.status(404).json({ message: "Profile not found" });
}
res.json(user);
} finally {
connection.release();
}
} catch (error) {
console.error(error);
res.status(500).json({ message: "Failed to retrieve profile", error: error.message });
}
});
// User Profile (PUT)
app.put(
"/api/profile",
upload.single("profilePicture"),
authenticateToken,
[
body("fullName").optional().notEmpty().withMessage("Full name is required"),
body("email").optional().isEmail().withMessage("Invalid email address"),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const userId = req.user.userId;
const {
fullName,
email,
bloodGroup,
medicalHistory,
currentPrescriptions,
phone,
bio,
qualification,
areasOfExpertise,
speciality,
availability,
bankAccount,
} = req.body;
const profilePicture = req.file ? req.file.path : null;
try {
const pool = getDb();
const connection = await pool.getConnection();
try {
let sql = "UPDATE users SET ";
const values = [];
// Only include non-null or non-empty fields in the update query
if (fullName && fullName.trim() !== "") {
sql += "fullName = ?, ";
values.push(fullName);
}
if (email && email.trim() !== "") {
sql += "email = ?, ";
values.push(email);
}
if (req.user.role === "user") {
if (bloodGroup && bloodGroup.trim() !== "") {
sql += "bloodGroup = ?, ";
values.push(bloodGroup);
}
if (medicalHistory && medicalHistory.trim() !== "") {
sql += "medicalHistory = ?, ";
values.push(medicalHistory);
}
if (currentPrescriptions && currentPrescriptions.trim() !== "") {
sql += "currentPrescriptions = ?, ";
values.push(currentPrescriptions);
}
} else if (req.user.role === "consultant") {
if (phone && phone.trim() !== "") {
sql += "phone = ?, ";
values.push(phone);
}
if (bio && bio.trim() !== "") {
sql += "bio = ?, ";
values.push(bio);
}
if (qualification && qualification.trim() !== "") {
sql += "qualification = ?, ";
values.push(qualification);
}
if (areasOfExpertise && areasOfExpertise.trim() !== "") {
sql += "areasOfExpertise = ?, ";
values.push(areasOfExpertise);
}
if (speciality && speciality.trim() !== "") {
sql += "speciality = ?, ";
values.push(speciality);
}
if (availability && availability.trim() !== "") {
sql += "availability = ?, ";
values.push(availability);