Skip to content

Commit

Permalink
Merge pull request #122 from agiledev-students-fall2023/anasofia
Browse files Browse the repository at this point in the history
stopTimes functions
  • Loading branch information
unfiltered-syrup authored Dec 5, 2023
2 parents 79f2e37 + c585dbc commit 3c1cdb8
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 15 deletions.
8 changes: 2 additions & 6 deletions back-end/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ const cron = require("node-cron");
const { fetchDataForRoutes } = require("./updateTimetable");

const mongoose = require("mongoose");
const Feedback = require("./models/Feedback.js");


// connect to the database
try {
mongoose.connect(process.env.MONGODB_URI);
console.log(`Connected to MongoDB.`);
Expand All @@ -25,18 +22,19 @@ try {
app.use(morgan("dev", { skip: (req, res) => process.env.NODE_ENV === "test" }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(cors({ origin: process.env.FRONT_END_DOMAIN, credentials: true }));

const feedbackRoutes = require("./routes/feedback-routes.js");
const timetableRoutes = require("./routes/timetable-routes.js");
const stopRoutes = require("./routes/stop-routes.js");

app.use("/feedback", feedbackRoutes());

app.get("/test", (req, res) => {
console.log(window.nyushuttle)
});
app.use("/timetable", timetableRoutes());
app.use("/stopfind", stopRoutes());

cron.schedule('0 0 * * *', () => {
fetchDataForRoutes(['routesA_W', 'routesA_F', 'routesA_Wknd', 'routesB_W',
Expand All @@ -46,8 +44,6 @@ cron.schedule('0 0 * * *', () => {

app.post("/getRoute", async (req, res) => {
const routeFinding = require("./getOptimizedRoute.js");


const busStops = {};
//parse stops into a dictionary of coordinates
for (let stopkey in req.body.stops) {
Expand Down
86 changes: 86 additions & 0 deletions back-end/routes/stop-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
const express = require("express");
const mongoose = require('mongoose');

const stopRoutes = () => {
const router = express.Router();

const getDayOfWeek = () => {
const today = new Date();
const dayOfWeek = today.getDay();
console.log(dayOfWeek);
return dayOfWeek;
}

const routeRuns = (route_name, day_of_week) => {
if (
(route_name === "B" && (day_of_week === 0 || day_of_week === 6)) ||
(route_name === "C" && (day_of_week === 0 || day_of_week === 6 || day_of_week === 5)) ||
(route_name === "E" && (day_of_week === 0 || day_of_week === 6)) ||
(route_name === "F" && (day_of_week === 0 || day_of_week === 6 || day_of_week === 5)) ||
(route_name === "W" && (day_of_week !== 0 && day_of_week !== 6))
) {
return false;
} else {
return true;
}
}

const dayToString = (day_of_week) => {
if (day_of_week === 0 || day_of_week === 6) {
return "Wknd";
} else if (day_of_week === 5) {
return "F";
} else {
return "Week";
}
}

router.get("/:stop_name/:route_name", async (req, res, next) => {
const day_of_week = getDayOfWeek();
console.log(day_of_week);
const { stop_name, route_name } = req.params;
console.log(stop_name, route_name, "rpint");
const runs = routeRuns(route_name, day_of_week);

if (!stop_name || !route_name) {
return res.status(401).json({
success: false,
message: "Invalid request. Please provide all required fields.",
});
}
if (!runs) {
return res.status(200).json({
success: true,
message: "Route is not running today.",
});
}
try {
const StopModel = mongoose.model('Route' + route_name + dayToString(day_of_week));
const stop = await StopModel.findOne({ stop_name: { $regex: new RegExp(stop_name, 'i') } });
if (!stop) {
console.log("Invalid request. Cannot find stop.")
return res.status(404).json({
success: false,
message: "Stop not found.",
});
}
return res.json({
success: true,
message: "Stop found.",
stop,
});
} catch (err) {
console.log("Invalid request. Please provide all required fields.")
console.error(`Error fetching stop: ${err}`);
return res.status(500).json({
success: false,
message: "Error looking up stop in the database.",
error: err,
});
}
});

return router;
}

module.exports = stopRoutes;
10 changes: 5 additions & 5 deletions back-end/routes/timetable-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ const timetableRouter = () => {
{ upsert: true, new: true }
);
if (!existingEntry) {
const newRoute = new Schema({
stop_name,
timestamp,
times,
}).save();
const newRoute = new Schema({
stop_name,
timestamp,
times,
}).save();
}
}
times = [];
Expand Down
1 change: 1 addition & 0 deletions front-end/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import TutorialComponent from './components/TutorialComponent';
import { registerService } from './utils/serviceRegister';
import { getMapCenter, loadGoogleMapsAPI } from './utils/mapUtility';
import { queryRoutes } from './utils/routes';
import { getNextTimes } from './utils/stopTimes';

// Import CSS
import './index.css';
Expand Down
75 changes: 75 additions & 0 deletions front-end/src/utils/stopTimes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import axios from "axios";

async function getShuttleTimes(stopName, route) {
const url = `http://localhost:4000/stopfind/${stopName}/${route}`;
return axios
.get(url)
.then((response) => {
console.log(response.data);
return response.data;
})
.catch((error) => {
console.error("Axios error:", error);
throw error;
});
}

async function getTimes(stopName, route) {
try {
const response = await getShuttleTimes(stopName, route);
const shuttleTimes = response.stop.times;
return shuttleTimes;
} catch (error) {
console.error("Function error:", error);
throw error;
}
}

export async function getNextTimes(stopName, route) {
try {
const currentTime = new Date();
const allTimes = await getTimes(stopName, route);
const upcomingTimes = allTimes
.map(timeString => {
const [time, period] = timeString.split(' ');
const [hours, minutes] = time.split(':');
let adjustedHours = parseInt(hours, 10);

if (period === 'PM' && adjustedHours !== 12) {
adjustedHours += 12;
}
const timeObject = new Date();
timeObject.setHours(adjustedHours, parseInt(minutes, 10));
return timeObject;
})
.filter(singleTime => {
return singleTime >= currentTime;
})
.map(time => time.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }));
console.log(upcomingTimes);
return upcomingTimes;
} catch (error) {
console.error("Function error:", error);
throw error;
}
}

export async function timeRemaining(stopName, route) {
try {
const currentTime = new Date();
const allTimes = await getNextTimes(stopName, route);
const upcomingTimes = allTimes.map(timeString => new Date(timeString));
const timeDifferences = upcomingTimes.map(upcomingTime => {
const differenceInMilliseconds = upcomingTime - currentTime;
const differenceInMinutes = differenceInMilliseconds / (1000 * 60);
return differenceInMinutes;
});
return timeDifferences;
} catch (error) {
console.error("Function error:", error);
throw error;
}
}


export default getShuttleTimes;
35 changes: 31 additions & 4 deletions front-end/src/utils/stops.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axios from 'axios';
import { timeRemaining, getMatchingName } from './stopTimes';
// import {} from './routes';

const MIN_QUERY_DELAY = 300000; // 5 min
Expand All @@ -11,6 +12,8 @@ if (typeof window.nyushuttle == 'undefined') {
}
window.nyushuttle.routePoints = {};
window.nyushuttle.stops = {};


window.nyushuttle.routes = [];
let center = {};
let stopMarkers = [];
Expand Down Expand Up @@ -259,13 +262,28 @@ function addRouteMarkersOnMap(routeId, routestops, routeGroupId, showStopName) {
if (isStopValid(theStop)) {
updateStopData(theStop, stop, routeId, routeGroupId, routeName, routeColor);
const marker = createMarkerForStop(theStop, zoomLevel, routeColor, showStopName, idx);
// marker.addListener('click', onMarkerClick);
// marker.addListener('mouseover', onMarkerHover);
marker.addListener('click', () => onMarkerClick(theStop, marker));
stopMarkers.push(marker);
}
});
}

function onMarkerClick(theStop, marker) {
const stopName = marker.title;
const route_id = theStop.routeName.slice(-1);
if(route_id && stopName){
console.log(route_id + " " + stopName);
//console.log(timeRemaining(getMatchingName(stopName, route_id), route_id));
}
}

function checkIfInfoisAvailable(route_id) {
if(route_id === "e" || route_id === "d"){
return "Real time info on this route not supported. Please check nyupassiogo."
}

}

function isStopValid(stop) {
return stop && stop.latitude != null && !(stop.latitude === 0.0 && stop.longitude === 0.0);
}
Expand Down Expand Up @@ -345,8 +363,17 @@ function recreateStopMarkerCluster() {
});

// Add event listeners to the marker cluster
// window.google.maps.event.addListener(stopMarkerCluster, 'click', onClusterMarkerClick);
// window.google.maps.event.addListener(stopMarkerCluster, 'mouseover', onClusterMarkerHover);
window.google.maps.event.addListener(stopMarkerCluster, 'click', onClusterMarkerClick);
//window.google.maps.event.addListener(stopMarkerCluster, 'mouseover', onClusterMarkerHover);
}

function onClusterMarkerClick(cluster) {
const markers = cluster.getMarkers();
for (let i = 0; i < markers.length; i++) {
const marker = markers[i];
const stopName = marker.title;
console.log(stopName);
}
}

function panToBoundsIfNeeded(center) {
Expand Down

0 comments on commit 3c1cdb8

Please sign in to comment.