-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
733 lines (622 loc) · 23.6 KB
/
Copy pathserver.ts
File metadata and controls
733 lines (622 loc) · 23.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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import express from "express";
import { createServer as createViteServer } from "vite";
import multer from "multer";
import cors from "cors";
import dotenv from "dotenv";
import path from "node:path";
import { fileURLToPath } from "node:url";
import axios from "axios";
import session from "express-session";
import mysql from "mysql2/promise";
import type { ResultSetHeader, RowDataPacket } from "mysql2";
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function getMysqlConfig() {
const rawConnectionString = process.env.MYSQL_CONNECTION_STRING || process.env.DATABASE_URL || "";
if (rawConnectionString) {
const normalized = rawConnectionString.startsWith("jdbc:")
? rawConnectionString.slice(5)
: rawConnectionString;
const url = new URL(normalized);
const userParam = url.searchParams.get("user");
let user = decodeURIComponent(url.username || userParam || process.env.MYSQL_USER || "root");
const password = decodeURIComponent(url.password || url.searchParams.get("password") || process.env.MYSQL_PASSWORD || "");
let database = url.pathname.replace(/^\/+/, "") || process.env.MYSQL_DATABASE || "";
// Accept JDBC-style value: ?user=root/intellisource
if (userParam?.includes("/")) {
const [parsedUser, parsedDb] = userParam.split("/");
user = parsedUser || user;
if (parsedDb) {
database = parsedDb;
}
}
if (!database) {
database = "intellisource";
}
return {
host: url.hostname || process.env.MYSQL_HOST || "localhost",
port: Number(url.port || process.env.MYSQL_PORT || 3306),
user,
password,
database,
};
}
return {
host: process.env.MYSQL_HOST || "localhost",
port: Number(process.env.MYSQL_PORT || 3306),
user: process.env.MYSQL_USER || "root",
password: process.env.MYSQL_PASSWORD || "",
database: process.env.MYSQL_DATABASE || "intellisource",
};
}
const mysqlConfig = getMysqlConfig();
const serverPool = mysql.createPool({
host: mysqlConfig.host,
port: mysqlConfig.port,
user: mysqlConfig.user,
password: mysqlConfig.password,
waitForConnections: true,
connectionLimit: 10,
});
const dbPool = mysql.createPool({
host: mysqlConfig.host,
port: mysqlConfig.port,
user: mysqlConfig.user,
password: mysqlConfig.password,
database: mysqlConfig.database,
waitForConnections: true,
connectionLimit: 10,
});
async function initDatabase() {
const ensureColumn = async (table: string, column: string, definition: string) => {
const [rows] = await dbPool.query<RowDataPacket[]>(
"SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1",
[mysqlConfig.database, table, column]
);
if (rows.length === 0) {
await dbPool.query(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
}
};
await serverPool.query(`CREATE DATABASE IF NOT EXISTS \`${mysqlConfig.database}\``);
await dbPool.query(`
CREATE TABLE IF NOT EXISTS users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
role VARCHAR(50) NOT NULL,
wallet_balance DECIMAL(10,2) DEFAULT 0.0,
vehicle_model VARCHAR(255),
plug_preference VARCHAR(255)
)
`);
await dbPool.query(`
CREATE TABLE IF NOT EXISTS charging_sources (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
host_id BIGINT,
location VARCHAR(255) NOT NULL,
lat DOUBLE,
lng DOUBLE,
plug_type VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
status VARCHAR(50) DEFAULT 'available',
amenities TEXT,
voltage INT DEFAULT 240,
max_current INT DEFAULT 32,
supported_vehicles TEXT,
FOREIGN KEY (host_id) REFERENCES users(id)
)
`);
await dbPool.query(`
CREATE TABLE IF NOT EXISTS bookings (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
driver_id BIGINT,
source_id BIGINT,
start_time DATETIME,
end_time DATETIME,
energy_consumed DECIMAL(10,2) DEFAULT 0.0,
total_cost DECIMAL(10,2) DEFAULT 0.0,
status VARCHAR(50) DEFAULT 'pending',
FOREIGN KEY (driver_id) REFERENCES users(id),
FOREIGN KEY (source_id) REFERENCES charging_sources(id)
)
`);
await dbPool.query(`
CREATE TABLE IF NOT EXISTS schedules (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
source_id BIGINT,
start_time DATETIME,
end_time DATETIME,
is_booked TINYINT(1) DEFAULT 0,
FOREIGN KEY (source_id) REFERENCES charging_sources(id)
)
`);
await dbPool.query(`
CREATE TABLE IF NOT EXISTS authorized_emails (
email VARCHAR(255) PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Ensure existing users remain able to sign in after enabling allowlist.
await dbPool.query("INSERT IGNORE INTO authorized_emails (email) SELECT LOWER(email) FROM users");
// Bring older schemas up to date without dropping existing data.
await ensureColumn("users", "vehicle_model", "VARCHAR(255)");
await ensureColumn("users", "plug_preference", "VARCHAR(255)");
await ensureColumn("users", "wallet_balance", "DECIMAL(10,2) DEFAULT 0.0");
await ensureColumn("charging_sources", "status", "VARCHAR(50) DEFAULT 'available'");
await ensureColumn("charging_sources", "lat", "DOUBLE");
await ensureColumn("charging_sources", "lng", "DOUBLE");
await ensureColumn("charging_sources", "plug_type", "VARCHAR(100) NOT NULL DEFAULT 'Type 2'");
await ensureColumn("charging_sources", "price", "DECIMAL(10,2) NOT NULL DEFAULT 0.0");
await ensureColumn("charging_sources", "amenities", "TEXT");
await ensureColumn("charging_sources", "voltage", "INT DEFAULT 240");
await ensureColumn("charging_sources", "max_current", "INT DEFAULT 32");
await ensureColumn("charging_sources", "supported_vehicles", "TEXT");
await ensureColumn("bookings", "start_time", "DATETIME");
await ensureColumn("bookings", "end_time", "DATETIME");
await ensureColumn("bookings", "energy_consumed", "DECIMAL(10,2) DEFAULT 0.0");
await ensureColumn("bookings", "total_cost", "DECIMAL(10,2) DEFAULT 0.0");
await ensureColumn("bookings", "status", "VARCHAR(50) DEFAULT 'pending'");
const [countRows] = await dbPool.query<RowDataPacket[]>("SELECT COUNT(*) as count FROM users");
const userCount = Number(countRows[0]?.count || 0);
const [chargerRows] = await dbPool.query<RowDataPacket[]>("SELECT COUNT(*) as count FROM charging_sources");
const chargerCount = Number(chargerRows[0]?.count || 0);
if (userCount === 0) {
await dbPool.query(
"INSERT INTO users (name, email, role, wallet_balance, vehicle_model, plug_preference) VALUES (?, ?, ?, ?, ?, ?)",
["John Driver", "driver@example.com", "driver", 100, "Tata Nexon", "CCS2"]
);
await dbPool.query(
"INSERT INTO users (name, email, role, wallet_balance, vehicle_model, plug_preference) VALUES (?, ?, ?, ?, ?, ?)",
["Alice Host", "host@example.com", "host", 50, "Nissan Leaf", "Type 2"]
);
await dbPool.query(
"INSERT IGNORE INTO authorized_emails (email) VALUES (?), (?)",
["driver@example.com", "host@example.com"]
);
}
if (chargerCount === 0) {
await dbPool.query(
"INSERT INTO charging_sources (host_id, location, lat, lng, plug_type, price, amenities, voltage, max_current, supported_vehicles) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[2, "123 Green St, Silicon Valley", 37.7749, -122.4194, "CCS2", 0.25, "Wi-Fi, Coffee", 240, 32, "Tesla, BMW, Hyundai, Tata, MG, Mahindra"]
);
await dbPool.query(
"INSERT INTO charging_sources (host_id, location, lat, lng, plug_type, price, amenities, voltage, max_current, supported_vehicles) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[2, "456 Eco Ave, Palo Alto", 37.4419, -122.143, "CCS2", 0.2, "Workspace, Restroom", 220, 16, "Nissan, Renault, VW, Tata, Hyundai, MG"]
);
const [sourceRows] = await dbPool.query<RowDataPacket[]>("SELECT id FROM charging_sources");
const now = new Date();
for (const source of sourceRows) {
for (let i = 0; i < 5; i++) {
const start = new Date(now.getTime() + i * 3600000);
const end = new Date(start.getTime() + 3600000);
await dbPool.query(
"INSERT INTO schedules (source_id, start_time, end_time) VALUES (?, ?, ?)",
[source.id, start, end]
);
}
}
}
const envAuthorizedEmails = (process.env.AUTHORIZED_EMAILS || "")
.split(",")
.map((email) => email.trim().toLowerCase())
.filter(Boolean);
if (envAuthorizedEmails.length > 0) {
const placeholders = envAuthorizedEmails.map(() => "(?)").join(",");
await dbPool.query(
`INSERT IGNORE INTO authorized_emails (email) VALUES ${placeholders}`,
envAuthorizedEmails
);
}
}
async function isEmailAuthorized(email: string) {
const normalizedEmail = email.trim().toLowerCase();
const [rows] = await dbPool.query<RowDataPacket[]>(
"SELECT email FROM authorized_emails WHERE email = ? LIMIT 1",
[normalizedEmail]
);
return rows.length > 0;
}
await initDatabase();
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
const isProduction = process.env.NODE_ENV === "production";
app.use(session({
secret: process.env.SESSION_SECRET || "ev-charger-secret",
resave: false,
saveUninitialized: false,
cookie: {
secure: isProduction,
sameSite: isProduction ? "none" : "lax",
httpOnly: true,
}
}));
// OAuth Routes
app.get("/api/auth/google/url", (req, res) => {
const clientId = process.env.GOOGLE_CLIENT_ID;
const appUrl = process.env.APP_URL || "http://localhost:3000";
if (!clientId || clientId === "MOCK_CLIENT_ID") {
console.error("Missing GOOGLE_CLIENT_ID in environment variables");
return res.status(500).json({ error: "OAuth configuration missing on server" });
}
const rootUrl = "https://accounts.google.com/o/oauth2/v2/auth";
const options = {
redirect_uri: `${appUrl}/auth/google/callback`,
client_id: clientId,
access_type: "offline",
response_type: "code",
prompt: "consent",
scope: [
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
].join(" "),
};
const qs = new URLSearchParams(options);
const authUrl = `${rootUrl}?${qs.toString()}`;
console.log("Initiating Google OAuth with Redirect URI:", options.redirect_uri);
res.json({ url: authUrl });
});
app.get("/api/auth/config", (req, res) => {
res.json({
googleClientId: process.env.GOOGLE_CLIENT_ID ? "Configured" : "Missing",
appUrl: process.env.APP_URL || "Not Set",
expectedRedirectUri: `${process.env.APP_URL || "http://localhost:3000"}/auth/google/callback`
});
});
app.get("/auth/google/callback", async (req, res) => {
const { code } = req.query;
try {
const tokenResponse = await axios.post("https://oauth2.googleapis.com/token", {
code,
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
redirect_uri: `${process.env.APP_URL || "http://localhost:3000"}/auth/google/callback`,
grant_type: "authorization_code",
});
const { access_token } = tokenResponse.data;
const userResponse = await axios.get("https://www.googleapis.com/oauth2/v2/userinfo", {
headers: { Authorization: `Bearer ${access_token}` },
});
const googleUser = userResponse.data;
const normalizedEmail = String(googleUser.email || "").trim().toLowerCase();
// Google-authenticated users are treated as authorized users.
await dbPool.query("INSERT IGNORE INTO authorized_emails (email) VALUES (?)", [normalizedEmail]);
const [existingRows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE email = ?", [normalizedEmail]);
let user = existingRows[0] as any;
if (!user) {
const [result] = await dbPool.query<ResultSetHeader>(
"INSERT INTO users (name, email, role, wallet_balance) VALUES (?, ?, ?, ?)",
[googleUser.name, normalizedEmail, "driver", 0]
);
const [createdRows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE id = ?", [result.insertId]);
user = createdRows[0];
}
(req.session as any).user = user;
res.send(`
<html>
<body style="background: #0A0A0A; color: white; font-family: sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0;">
<div style="text-align: center;">
<h2 style="color: #00FF00;">Authentication Successful</h2>
<p style="opacity: 0.6;">Welcome, ${user.name}! Closing this window...</p>
<script>
if (window.opener) {
window.opener.postMessage({ type: 'OAUTH_AUTH_SUCCESS' }, '*');
window.close();
} else {
window.location.href = '/';
}
</script>
</div>
</body>
</html>
`);
} catch (error: any) {
console.error("Google Auth Error:", error.response?.data || error.message);
res.status(500).send("Authentication failed");
}
});
app.post("/api/auth/login", async (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: "Email is required" });
}
const normalizedEmail = String(email).trim().toLowerCase();
const authorized = await isEmailAuthorized(normalizedEmail);
if (!authorized) {
return res.status(403).json({ error: "This account is not authorized. Contact admin for access." });
}
const [rows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE email = ?", [normalizedEmail]);
let user = rows[0] as any;
if (!user) {
const [result] = await dbPool.query<ResultSetHeader>(
"INSERT INTO users (name, email, role, wallet_balance) VALUES (?, ?, ?, ?)",
[normalizedEmail.split("@")[0], normalizedEmail, "driver", 100]
);
const [createdRows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE id = ?", [result.insertId]);
user = createdRows[0];
}
(req.session as any).user = user;
res.json(user);
});
app.get("/api/auth/me", (req, res) => {
const user = (req.session as any).user;
if (user) {
res.json(user);
} else {
res.status(401).json({ error: "Not authenticated" });
}
});
app.post("/api/auth/logout", (req, res) => {
req.session.destroy(() => {
res.json({ success: true });
});
});
const upload = multer({ storage: multer.memoryStorage() });
void upload;
class ChargerService {
static async getAll() {
const [rows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM charging_sources");
return rows;
}
static async getByHost(hostId: number) {
const [rows] = await dbPool.query<RowDataPacket[]>(
"SELECT * FROM charging_sources WHERE host_id = ? ORDER BY id DESC",
[hostId]
);
return rows;
}
static async create(data: any) {
const { host_id, location, lat, lng, plug_type, price, amenities } = data;
const [result] = await dbPool.query<ResultSetHeader>(
"INSERT INTO charging_sources (host_id, location, lat, lng, plug_type, price, amenities) VALUES (?, ?, ?, ?, ?, ?, ?)",
[host_id, location, lat, lng, plug_type, price, amenities]
);
return { id: result.insertId };
}
static async deleteOwned(chargerId: number, hostId: number) {
const [result] = await dbPool.query<ResultSetHeader>(
"DELETE FROM charging_sources WHERE id = ? AND host_id = ?",
[chargerId, hostId]
);
return result.affectedRows > 0;
}
}
app.get("/api/chargers/:id/schedules", async (req, res) => {
const [rows] = await dbPool.query<RowDataPacket[]>(
"SELECT * FROM schedules WHERE source_id = ? AND is_booked = 0 ORDER BY start_time ASC",
[req.params.id]
);
res.json(rows);
});
app.post("/api/users/update", async (req, res) => {
const user = (req.session as any).user;
if (!user) {
return res.status(401).json({ error: "Not authenticated" });
}
const { vehicle_model, plug_preference } = req.body;
await dbPool.query(
"UPDATE users SET vehicle_model = ?, plug_preference = ? WHERE id = ?",
[vehicle_model, plug_preference, user.id]
);
const [rows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE id = ?", [user.id]);
const updatedUser = rows[0];
(req.session as any).user = updatedUser;
res.json(updatedUser);
});
app.get("/api/chargers", async (req, res) => {
try {
const chargers = await ChargerService.getAll();
res.json(chargers);
} catch {
res.status(500).json({ error: "Failed to fetch chargers" });
}
});
app.get("/api/chargers/mine", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to view your hosted chargers." });
}
try {
const chargers = await ChargerService.getByHost(sessionUser.id);
res.json(chargers);
} catch {
res.status(500).json({ error: "Failed to fetch your chargers" });
}
});
app.post("/api/chargers", async (req, res) => {
try {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to host a charger." });
}
const payload = {
...req.body,
host_id: sessionUser.id,
};
const result = await ChargerService.create(payload);
res.json(result);
} catch {
res.status(500).json({ error: "Failed to create charger" });
}
});
app.delete("/api/chargers/:id", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to delete a hosted charger." });
}
const chargerId = Number(req.params.id);
if (Number.isNaN(chargerId)) {
return res.status(400).json({ error: "Invalid charger id." });
}
try {
const deleted = await ChargerService.deleteOwned(chargerId, sessionUser.id);
if (!deleted) {
return res.status(404).json({ error: "Charger not found or you are not allowed to delete it." });
}
res.json({ success: true });
} catch {
res.status(500).json({ error: "Failed to delete charger" });
}
});
app.post("/api/bookings", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to book a charger." });
}
const sourceId = Number(req.body?.source_id);
if (!Number.isInteger(sourceId) || sourceId <= 0) {
return res.status(400).json({ error: "Valid source_id is required." });
}
const conn = await dbPool.getConnection();
try {
await conn.beginTransaction();
const [sourceRows] = await conn.query<RowDataPacket[]>(
"SELECT id FROM charging_sources WHERE id = ? FOR UPDATE",
[sourceId]
);
if (sourceRows.length === 0) {
await conn.rollback();
return res.status(404).json({ error: "Charger not found." });
}
const startTime = new Date();
const endTime = new Date(startTime.getTime() + 60 * 60 * 1000);
const [result] = await conn.query<ResultSetHeader>(
"INSERT INTO bookings (driver_id, source_id, start_time, end_time, status) VALUES (?, ?, ?, ?, ?)",
[sessionUser.id, sourceId, startTime, endTime, "pending"]
);
await conn.commit();
res.json({ id: result.insertId });
} catch (error) {
await conn.rollback();
console.error("Booking failed:", error);
res.status(500).json({ error: "Failed to create booking" });
} finally {
conn.release();
}
});
app.post("/api/bookings/:id/start", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to start a booked session." });
}
const bookingId = Number(req.params.id);
if (!Number.isInteger(bookingId) || bookingId <= 0) {
return res.status(400).json({ error: "Invalid booking id." });
}
try {
const [rows] = await dbPool.query<RowDataPacket[]>(
"SELECT id, status, source_id FROM bookings WHERE id = ? AND driver_id = ?",
[bookingId, sessionUser.id]
);
if (rows.length === 0) {
return res.status(404).json({ error: "Booking not found." });
}
const booking = rows[0];
const currentStatus = String(booking.status || "pending").toLowerCase();
if (currentStatus === "cancelled" || currentStatus === "completed") {
return res.status(409).json({ error: `Cannot start a ${currentStatus} booking.` });
}
await dbPool.query(
"UPDATE bookings SET status = ? WHERE id = ? AND driver_id = ?",
["active", bookingId, sessionUser.id]
);
res.json({ success: true, id: bookingId, source_id: Number(booking.source_id), status: "active" });
} catch (error) {
console.error("Failed to start booking session:", error);
res.status(500).json({ error: "Failed to start booking session" });
}
});
app.get("/api/bookings/me", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to view your bookings." });
}
try {
const [rows] = await dbPool.query<RowDataPacket[]>(
`SELECT
b.id,
b.source_id,
b.start_time,
b.end_time,
b.energy_consumed,
b.total_cost,
b.status,
c.location AS charger_location,
c.lat AS charger_lat,
c.lng AS charger_lng,
c.plug_type AS charger_plug_type,
c.price AS charger_price
FROM bookings b
INNER JOIN charging_sources c ON c.id = b.source_id
WHERE b.driver_id = ?
ORDER BY b.id DESC`,
[sessionUser.id]
);
res.json(rows);
} catch (error) {
console.error("Failed to load bookings:", error);
res.status(500).json({ error: "Failed to load bookings" });
}
});
app.delete("/api/bookings/me", async (req, res) => {
const sessionUser = (req.session as any).user;
if (!sessionUser) {
return res.status(401).json({ error: "Please log in to clear your booking history." });
}
const conn = await dbPool.getConnection();
try {
await conn.beginTransaction();
const [idempotencyTableRows] = await conn.query<RowDataPacket[]>(
"SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1",
[mysqlConfig.database, "booking_idempotency"]
);
if (idempotencyTableRows.length > 0) {
await conn.query(
`DELETE bi
FROM booking_idempotency bi
INNER JOIN bookings b ON b.id = bi.booking_id
WHERE b.driver_id = ?`,
[sessionUser.id]
);
}
const [result] = await conn.query<ResultSetHeader>(
"DELETE FROM bookings WHERE driver_id = ?",
[sessionUser.id]
);
await conn.commit();
res.json({ success: true, deletedCount: Number(result.affectedRows || 0) });
} catch (error) {
await conn.rollback();
console.error("Failed to clear booking history:", error);
res.status(500).json({ error: "Failed to clear booking history" });
} finally {
conn.release();
}
});
app.get("/api/users/:email", async (req, res) => {
const [rows] = await dbPool.query<RowDataPacket[]>("SELECT * FROM users WHERE email = ?", [req.params.email]);
const user = rows[0];
if (user) {
res.json(user);
} else {
res.status(404).json({ error: "User not found" });
}
});
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.join(__dirname, "dist")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Connected MySQL database: ${mysqlConfig.database}`);
});