-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
563 lines (500 loc) · 15.8 KB
/
index.js
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
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const path = require("path");
const ejsMate = require("ejs-mate");
const flash = require("connect-flash");
const session = require("express-session");
const passport = require("passport");
const localStrategy = require("passport-local");
const bodyParser = require("body-parser");
const MongoStore = require("connect-mongo");
const methodOverride = require("method-override");
const expressError = require("./utils/expressError");
const User = require("./models/user");
const Bus = require("./models/bus");
const Route = require("./models/route");
const Booking = require("./models/booking");
const booking = require("./models/booking");
const app = express();
app.use(express.urlencoded({ extended: true }));
const dbUrl = "mongodb://127.0.0.1:27017/busBuddy";
mongoose.set("strictQuery", true);
mongoose.connect(dbUrl);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const sessionStore = new MongoStore({
mongoUrl: dbUrl,
mongooseConnection: mongoose.connection,
collection: "sessions", // Collection name for sessions in MongoDB
});
const sessionConfig = {
name: "tappu",
secret: "thisShouldBeSecret",
resave: false,
saveUninitialized: true,
store: sessionStore,
cookie: {
httpOnly: true,
// secure: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
};
app.engine("ejs", ejsMate);
app.use(session(sessionConfig));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views/"));
app.use(express.static(path.join(__dirname, "public")));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride("_method"));
passport.use(new localStrategy(User.authenticate()));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.originalUrl = req.originalUrl;
res.locals.success = req.flash("success");
res.locals.error = req.flash("error");
next();
});
const isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.flash("error", "You need to login first");
return res.redirect("/login");
}
next();
};
const getCurrentTime = () => {
const currentTime = new Date();
// Extract hours and minutes
const currentHours = currentTime.getHours();
const currentMinutes = currentTime.getMinutes();
return { currentHours, currentMinutes };
};
const hoursToMinute = (hour, min) => {
return 60 * hour + min;
};
const getActiveTripForUser = (min, user) => {
let activeTrips = 0,
upcomingTrips = 0,
finishedTrips = 0;
if (user.buses.length) {
for (let bus of user.buses) {
if (bus && bus.routes && bus.routes.length > 0) {
for (let route of bus.routes) {
const startMin = hoursToMinute(
route.startTime.hours,
route.startTime.minutes
);
const endMin = hoursToMinute(
route.endTime.hours,
route.endTime.minutes
);
if (min < startMin) {
upcomingTrips = upcomingTrips + 1;
} else if (min >= startMin && min <= endMin) {
activeTrips = activeTrips + 1;
} else {
finishedTrips = finishedTrips + 1;
}
}
}
}
}
return { activeTrips, upcomingTrips, finishedTrips };
};
const getActiveTripForTraveller = (min, routes) => {
let activeTrips = 0,
upcomingTrips = 0,
finishedTrips = 0;
if (routes.length){
for (let route of routes) {
const startMin = hoursToMinute(
route.startTime.hours,
route.startTime.minutes
);
const endMin = hoursToMinute(
route.endTime.hours,
route.endTime.minutes
);
if (min < startMin) {
upcomingTrips = upcomingTrips + 1;
} else if (min >= startMin && min <= endMin) {
activeTrips = activeTrips + 1;
} else {
finishedTrips = finishedTrips + 1;
}
}
}
return { activeTrips, upcomingTrips, finishedTrips };
};
app.get("", async (req, res) => {
// const id = "662a4f9d90c39952acbe1a9b";
// const id = "662a735c10ed8a265ee7ee21";
// const routeData = await routeModel.findOne({ id });
// Extract coordinates from each stop
// const stopCoordinates = routeData.stop.map((e) => ({
// lat: e.location.geometery.coordinates[0],
// long: e.location.geometery.coordinates[1],
// }));
// Log coordinates
// console.log(stopCoordinates);
// Render response
res.render("home");
});
app.get("/dashboard", isLoggedIn, async (req, res) => {
const user = await User.findById(req.user._id);
let populatedUser;
if (user.type === "operator") {
// Populate buses and routes if the user is an operator
populatedUser = await User.findById(req.user._id)
.populate({
path: "buses",
populate: {
path: "routes",
},
})
.populate('booking');
console.log(populatedUser);
const { currentHours, currentMinutes } = getCurrentTime();
const totalMin = hoursToMinute(currentHours, currentMinutes);
const { activeTrips, finishedTrips, upcomingTrips } =
getActiveTripForUser(totalMin, populatedUser);
console.log(activeTrips,finishedTrips)
res.render("dashboard", {
user: populatedUser,
activeTrips,
finishedTrips,
upcomingTrips,
});
} else if (user.type === "traveller") {
// Populate bookings if the user is a traveller
populatedUser = await User.findById(req.user._id)
.populate({path: "booking",
populate: {
path: "route",
}});
console.log(populatedUser);
res.render("dashboard", {
user: populatedUser
});
}
});
app.get("/my-buses", isLoggedIn, async (req, res) => {
const user = await User.findById(req.user._id).populate("buses");
res.render("my-buses", { user });
});
app.post("/add-bus", isLoggedIn, async (req, res) => {
const { busName, busNumber, type, driver, conductor, busContact, seats } =
req.body;
const user = await User.findById(req.user._id);
const bus = await new Bus({
busName,
busNumber,
type,
driver,
conductor,
busContact,
seats,
});
bus.user = req.user._id;
user.buses.push(bus);
await user.save();
await bus.save();
console.log(user);
console.log(bus);
req.flash("success", `Added new bus ${bus.busName}`);
res.redirect("/my-buses");
});
app.get("/bus/:id", isLoggedIn, async (req, res) => {
const busData = await Bus.findById(req.params.id).populate("routes");
res.render("bus", { busData });
});
app.post("/bus/:id", async (req, res) => {
const {
routeName,
totalStops,
startTime,
endTime,
startStop,
endStop,
stop,
} = req.body;
const formatTime = (time) => {
const [hours, minutes] = time.split(":").map(Number);
return { hours, minutes };
};
const calculateTotalTime = (startTime, endTime) => {
const parseTime = (time) => {
const [hours, minutes] = time.split(":").map(Number);
return { hours, minutes };
};
const start = parseTime(startTime);
const end = parseTime(endTime);
const startMinutes = start.hours * 60 + start.minutes;
const endMinutes = end.hours * 60 + end.minutes;
let totalMinutes;
if (endMinutes >= startMinutes) {
totalMinutes = endMinutes - startMinutes;
} else {
totalMinutes = 24 * 60 - startMinutes + endMinutes; // Crosses midnight
}
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
return `${hours}:${minutes}`;
};
formattedStartTime = formatTime(startTime);
formattedEndTime = formatTime(endTime);
formattedTotalTime = formatTime(calculateTotalTime(startTime, endTime));
// Process the stop array
const formattedStops = stop.map((s) => ({
name: s.name,
coords: s.coords,
arrivalTime: formatTime(s.arrTime),
departureTime: formatTime(s.deptTime),
}));
console.log(formattedStops);
const route = await new Route({
routeName,
totalStops,
startStop,
endStop,
startTime: formattedStartTime,
endTime: formattedEndTime,
totalTime: formattedTotalTime,
stops: formattedStops,
bus: req.params.id,
});
await route.save();
// formattedStartTime: startTime,
// formattedEndTime: endTime,
// stops: formattedStops,
const bus = await Bus.findById(req.params.id);
bus.routes.push(route._id);
await bus.save();
res.redirect(`/bus/${req.params.id}`);
});
app.delete("/bus/:id", async (req, res) => {
try {
const bus = await Bus.findByIdAndDelete(req.params.id).populate("routes");
const routes = bus.routes.forEach(
async (e) => await Route.findByIdAndDelete(e._id)
);
req.flash(
"success",
`Successfully deleted ${bus.busName} bus and its respective routes`
);
res.redirect("/my-buses");
} catch (e) {
req.flash("error", e.message);
console.log("error" + e);
res.redirect("/my-buses");
}
});
app.get("/route/:routeId/booking", isLoggedIn, async(req,res) => {
const route = await Route.findById(req.params.routeId);
res.render('booking',{route});
})
app.post("/route/:routeId/booking", isLoggedIn, async(req,res) => {
const {selectedSeats,selectedDate} = req.body;
const {routeId} = req.params;
const seats = selectedSeats.split(',').map(Number);
const today = new Date();
const bookingDate = new Date(
today.setDate(today.getDate() + parseInt(selectedDate))
);
const route = await Route.findById(routeId);
const ticket = await new Booking({route: routeId, seatsBooked: seats, user: req.user._id , travelDate: bookingDate })
await ticket.save();
const user = await User.findById(req.user._id);
user.booking.push(ticket._id);
await user.save();
if(ticket){
req.flash("success", `Booking done for ${route.startStop} - ${route.endStop}`);
res.redirect("/dashboard");
} else {
req.flash("error","Encountered some error");
res.redirect(`/route/${routeId}/booking`);
}
})
app.get("/route/:routeId",async(req,res) => {
const route = await Route.findById(req.params.routeId);
res.render('route',{route});
})
app.delete("/route/:routeId", async (req, res) => {
try {
const route = await Route.findByIdAndDelete(req.params.routeId).populate(
"bus"
);
console.log(route);
const bus = await Bus.findById(route.bus._id);
bus.routes.pull(req.params.routeId);
await bus.save();
req.flash("success", `Successfully deleted ${route.routeName} route`);
res.redirect(`/bus/${route.bus._id}`); // Corrected redirection URL
} catch (error) {
console.error(error);
req.flash("error", "An error occurred");
res.redirect(`/bus/${route.bus._id}`);
}
});
app.get("/register", (req, res) => {
res.render("users/register");
});
app.get("/results", async (req, res) => {
const { startStop, endStop } = req.query;
try {
// Validate input
if (!startStop || !endStop) {
req.flash("error", "Both start and end stops are required.");
return res.redirect("/");
}
// Query the database
const routes = await Route.find({
"stops.name": { $all: [startStop, endStop] },
}).populate("bus");
// Filter routes to ensure the start stop comes before the end stop
const filteredRoutes = routes.filter((route) => {
const startIndex = route.stops.findIndex(
(stop) => stop.name === startStop
);
const endIndex = route.stops.findIndex((stop) => stop.name === endStop);
return startIndex !== -1 && endIndex !== -1 && startIndex < endIndex;
});
// Handle no results
if (filteredRoutes.length === 0) {
req.flash("error", "No routes found for the specified stops.");
return res.redirect("/");
}
const { currentHours, currentMinutes } = getCurrentTime();
const totalMin = hoursToMinute(currentHours, currentMinutes);
// const { activeTrips, upcomingTrips, finishedTrips } =
// getActiveTripForTraveller(totalMin, filteredRoutes);
// filter routes acc to current time
filteredRoutes.sort((a, b) => {
const aStartTime = hoursToMinute(a.startTime.hours, a.startTime.minutes);
const aEndTime = hoursToMinute(a.endTime.hours, a.endTime.minutes);
const bStartTime = hoursToMinute(b.startTime.hours, b.startTime.minutes);
const bEndTime = hoursToMinute(b.endTime.hours, b.endTime.minutes);
if (aStartTime >= totalMin && bStartTime >= totalMin) {
return aStartTime - bStartTime; // Both are future starts, sort by closest start time
} else if (aStartTime >= totalMin && bStartTime < totalMin) {
return -1; // a is future, b is past, a comes first
} else if (aStartTime < totalMin && bStartTime >= totalMin) {
return 1; // a is past, b is future, b comes first
} else {
// Both are past starts, sort by closest end time
return aEndTime - bEndTime;
}
});
// Separate routes into active, upcoming, and finished
const activeTrips = filteredRoutes.filter((route) => {
const startTime = hoursToMinute(
route.startTime.hours,
route.startTime.minutes
);
const endTime = hoursToMinute(
route.endTime.hours,
route.endTime.minutes
);
return startTime <= totalMin && endTime >= totalMin;
});
const upcomingTrips = filteredRoutes.filter((route) => {
const startTime = hoursToMinute(
route.startTime.hours,
route.startTime.minutes
);
return startTime > totalMin;
});
const finishedTrips = filteredRoutes.filter((route) => {
const endTime = hoursToMinute(
route.endTime.hours,
route.endTime.minutes
);
return endTime < totalMin;
})
const totalTrips = [...activeTrips,...upcomingTrips,...finishedTrips];
// Render the results page
res.render("traveller", {
filteredRoutes,
startStop,
endStop,
activeTrips,
upcomingTrips,
finishedTrips,
totalTrips,
});
} catch (error) {
console.error("Error fetching routes:", error);
req.flash("error", "Something went wrong. Please try again later.");
res.send(error);
}
});
app.post("/register", async (req, res) => {
try {
const { name, email, username, password, type } = req.body;
const user = await new User({
name,
username,
email,
type,
});
const registeredUser = await User.register(user, password);
req.login(registeredUser, (err) => {
if (err) return next(err);
req.flash("success", `Welcome ${req.user.name}`);
console.log("Hogya regsiter bhai");
res.redirect("/dashboard");
});
} catch (e) {
req.flash("error", e.message);
console.log("error" + e);
res.redirect("/login");
}
});
app.get("/login", (req, res) => {
res.render("users/login");
});
app.post(
"/login",
passport.authenticate("local", {
failureFlash: true,
failureRedirect: "/login",
}),
async (req, res) => {
req.flash("success", `Welcome ${req.user.name}`);
res.redirect("/dashboard");
}
);
app.get("/logout", (req, res) => {
req.logout(function (err) {
if (err) {
res.send(err);
}
req.flash("success", "Successfully, Logged Out!");
res.redirect("/");
});
});
app.get("/about", (req, res) => {
res.send("about");
});
app.post("/routes", async (req, res) => {});
app.all("*", (req, res, next) => {
next(new expressError("Page not found", 404));
});
app.use((err, req, res, next) => {
const { statusCode = 500 } = err;
if (!err.message) err.message = "Something went wrong";
res.status(statusCode).render("error", { error: err });
});
app.listen("3000", () => {
console.log("Listening on port 3000");
});