logo added to login pageand code reformatted using prettier

This commit is contained in:
2024-05-02 05:17:01 -06:00
parent 48e3f7623d
commit 717b41bec0
19 changed files with 712 additions and 709 deletions

View File

@@ -1,4 +1,4 @@
<img src="src/assets/img/logo.png" width="80%"/> <img src="src/assets/img/logo.png" width="80%">
# Welcome to ScoreSpot # Welcome to ScoreSpot
@@ -56,8 +56,7 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
**Once the following dependencies above are installed navigate to the top of the repsoitory and copy the following link:** **Once the following dependencies above are installed navigate to the top of the repsoitory and copy the following link:**
> https://github.com/LucasPatenaude/ScoreSpot.git > <https://github.com/LucasPatenaude/ScoreSpot.git>
**Using a Git GUI or the terminal select a location to store the repository. In this example, I'll store it in a folder called `programming` in the home directory** **Using a Git GUI or the terminal select a location to store the repository. In this example, I'll store it in a folder called `programming` in the home directory**
@@ -71,24 +70,18 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
`cd /c/Users/<YourUsername>` <--- Replace with your windows user name `cd /c/Users/<YourUsername>` <--- Replace with your windows user name
2. In the home directory create a folder called `programming` 2. In the home directory create a folder called `programming`
> On All Systems > On All Systems
`mkdir programming` `mkdir programming`
3. Now that `programming` is created navigate to it 3. Now that `programming` is created navigate to it
> On All Systems > On All Systems
`cd programming` `cd programming`
4. **Now that you're in the `~/programming` directory it's time to clone the repository** 4. **Now that you're in the `~/programming` directory it's time to clone the repository**
> On All Systems > On All Systems

View File

@@ -1,4 +1,4 @@
version: '3.9' version: "3.9"
services: services:
db: db:
@@ -9,14 +9,14 @@ services:
POSTGRES_PASSWORD: "pwd" POSTGRES_PASSWORD: "pwd"
POSTGRES_DB: "users_db" POSTGRES_DB: "users_db"
ports: ports:
- '5432:5432' - "5432:5432"
volumes: volumes:
- users-database:/var/lib/postgresql/data - users-database:/var/lib/postgresql/data
- ./public/init_data:/docker-entrypoint-initdb.d - ./public/init_data:/docker-entrypoint-initdb.d
web: web:
container_name: node-web-interface container_name: node-web-interface
image: node:lts image: node:lts
user: 'node' user: "node"
working_dir: /home/node/app working_dir: /home/node/app
environment: environment:
NODE_ENV: development NODE_ENV: development
@@ -25,11 +25,11 @@ services:
depends_on: depends_on:
- db - db
ports: ports:
- '3000:3000' - "3000:3000"
volumes: volumes:
- .:/home/node/app # Mount Client directory - .:/home/node/app # Mount Client directory
- ./node_modules:/home/node/app/node_modules # Mount node_modules directory - ./node_modules:/home/node/app/node_modules # Mount node_modules directory
command: 'npm run start' command: "npm run start"
volumes: volumes:
users-database: users-database:

235
index.js
View File

@@ -2,17 +2,17 @@
// <!-- Section 1 : Import Dependencies --> // <!-- Section 1 : Import Dependencies -->
// ***************************************************** // *****************************************************
const express = require('express'); // To build an application server or API const express = require("express"); // To build an application server or API
const app = express(); const app = express();
const handlebars = require('express-handlebars'); const handlebars = require("express-handlebars");
const Handlebars = require('handlebars'); const Handlebars = require("handlebars");
const path = require('path'); const path = require("path");
const pgp = require('pg-promise')(); // To connect to the Postgres DB from the node server const pgp = require("pg-promise")(); // To connect to the Postgres DB from the node server
const bodyParser = require('body-parser'); const bodyParser = require("body-parser");
const session = require('express-session'); // To set the session object. To store or access session data, use the `req.session`, which is (generally) serialized as JSON by the store. const session = require("express-session"); // To set the session object. To store or access session data, use the `req.session`, which is (generally) serialized as JSON by the store.
const bcrypt = require('bcryptjs'); // To hash passwords const bcrypt = require("bcryptjs"); // To hash passwords
const axios = require('axios'); // To make HTTP requests from our server. We'll learn more about it in Part C. const axios = require("axios"); // To make HTTP requests from our server. We'll learn more about it in Part C.
const moment = require('moment'); // To extract current time data const moment = require("moment"); // To extract current time data
// ***************************************************** // *****************************************************
// <!-- Section 2 : Connect to DB --> // <!-- Section 2 : Connect to DB -->
@@ -20,32 +20,31 @@ const moment = require('moment'); // To extract current time data
// create `ExpressHandlebars` instance and configure the layouts and partials dir. // create `ExpressHandlebars` instance and configure the layouts and partials dir.
const hbs = handlebars.create({ const hbs = handlebars.create({
extname: 'hbs', extname: "hbs",
layoutsDir: __dirname + '/src/views/layouts', layoutsDir: __dirname + "/src/views/layouts",
partialsDir: __dirname + '/src/views/partials', partialsDir: __dirname + "/src/views/partials",
}); });
// database configuration // database configuration
// database configuration // database configuration
const dbConfig = { const dbConfig = {
host: 'db', // the database server host: "db", // the database server
port: 5432, // the database port port: 5432, // the database port
database: "users_db", // the database name database: "users_db", // the database name
user: "postgres", // the user account to connect with user: "postgres", // the user account to connect with
password: "pwd", // the password of the user account password: "pwd", // the password of the user account
}; };
const db = pgp(dbConfig); const db = pgp(dbConfig);
// test your database // test your database
db.connect() db.connect()
.then(obj => { .then((obj) => {
console.log('Database connection successful'); // you can view this message in the docker compose logs console.log("Database connection successful"); // you can view this message in the docker compose logs
obj.done(); // success, release the connection; obj.done(); // success, release the connection;
}) })
.catch(error => { .catch((error) => {
console.log('ERROR:', error.message || error); console.log("ERROR:", error.message || error);
}); });
// ***************************************************** // *****************************************************
@@ -53,14 +52,14 @@ db.connect()
// ***************************************************** // *****************************************************
// Register `hbs` as our view engine using its bound `engine()` function. // Register `hbs` as our view engine using its bound `engine()` function.
app.engine('hbs', hbs.engine); app.engine("hbs", hbs.engine);
app.set('view engine', 'hbs'); app.set("view engine", "hbs");
app.set('views', path.join(__dirname, '/src/views')); app.set("views", path.join(__dirname, "/src/views"));
app.use(bodyParser.json()); // specify the usage of JSON for parsing request body. app.use(bodyParser.json()); // specify the usage of JSON for parsing request body.
// initialize session variables // initialize session variables
app.get('/welcome', (req, res) => { app.get("/welcome", (req, res) => {
res.json({status: 'success', message: 'Welcome!'}); res.json({ status: "success", message: "Welcome!" });
}); });
app.use( app.use(
session({ session({
@@ -75,14 +74,16 @@ app.use(
extended: true, extended: true,
}) })
); );
app.use(async function(req, res, next) { app.use(async function (req, res, next) {
res.locals.user = req.session.user; res.locals.user = req.session.user;
if(res.locals.user) { if (res.locals.user) {
try { try {
res.locals.fav_teams = await getFavoriteTeamsForUser(res.locals.user.userid); res.locals.fav_teams = await getFavoriteTeamsForUser(
res.locals.user.userid
);
} catch (error) { } catch (error) {
console.error('Error fetching favorite teams:', error); console.error("Error fetching favorite teams:", error);
} }
} }
@@ -90,62 +91,64 @@ app.use(async function(req, res, next) {
}); });
// Serve static files from the 'public' directory // Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, '/src/assets'))); app.use(express.static(path.join(__dirname, "/src/assets")));
// ***************************************************** // *****************************************************
// <!-- Section 4 : Middleware --> // <!-- Section 4 : Middleware -->
// ***************************************************** // *****************************************************
// Middleware to automatically update live scoreboard // Middleware to automatically update live scoreboard
const fetchMatchesData = require('./src/assets/middleware/navigation-bar/current-match-information'); const fetchMatchesData = require("./src/assets/middleware/navigation-bar/current-match-information");
app.use(fetchMatchesData); app.use(fetchMatchesData);
//Middleware to automatically update in-game time abbreviations //Middleware to automatically update in-game time abbreviations
const convert_time = require('./src/assets/middleware/navigation-bar/convert-time'); const convert_time = require("./src/assets/middleware/navigation-bar/convert-time");
app.use(convert_time); app.use(convert_time);
// Leagues Page Middleware // Leagues Page Middleware
const fetchLeaguesData = require('./src/assets/middleware/leagues-page/get-current-league-information'); const fetchLeaguesData = require("./src/assets/middleware/leagues-page/get-current-league-information");
const fetchLeagueScorerData = require('./src/assets/middleware/leagues-page/get-current-league-top-scorers'); const fetchLeagueScorerData = require("./src/assets/middleware/leagues-page/get-current-league-top-scorers");
app.get('/league/:leagueID', [fetchLeaguesData, fetchLeagueScorerData], (req, res) => { app.get(
"/league/:leagueID",
[fetchLeaguesData, fetchLeagueScorerData],
(req, res) => {
// Render the Handlebars view with league data // Render the Handlebars view with league data
res.render('pages/leagues-page', { res.render("pages/leagues-page", {
leagueID: req.params.leagueID, leagueID: req.params.leagueID,
leagues: res.locals.leagues, leagues: res.locals.leagues,
scorers: res.locals.topScorers // Assuming fetchLeagueScorerData sets the data in res.locals.scorers scorers: res.locals.topScorers, // Assuming fetchLeagueScorerData sets the data in res.locals.scorers
}); });
}); }
);
// Clubs Page Middleware // Clubs Page Middleware
const fetchClubsData = require('./src/assets/middleware/clubs-page/get-current-club-information'); const fetchClubsData = require("./src/assets/middleware/clubs-page/get-current-club-information");
app.get('/club/:clubID', [fetchClubsData], (req, res) => { app.get("/club/:clubID", [fetchClubsData], (req, res) => {
// Render the Handlebars view with league data // Render the Handlebars view with league data
var isFav = false; var isFav = false;
var fav_teams = res.locals.fav_teams; var fav_teams = res.locals.fav_teams;
if(res.locals.user && fav_teams) if (res.locals.user && fav_teams) {
{ const isTeamIDInFavTeams = fav_teams.some((team) => {
const isTeamIDInFavTeams = fav_teams.some(team => {
const teamIdInt = parseInt(team.teamid); const teamIdInt = parseInt(team.teamid);
const clubIdInt = parseInt(req.params.clubID); const clubIdInt = parseInt(req.params.clubID);
console.log('Checking team:', teamIdInt); console.log("Checking team:", teamIdInt);
console.log('equal to', clubIdInt); console.log("equal to", clubIdInt);
return teamIdInt === clubIdInt; return teamIdInt === clubIdInt;
}); });
if (isTeamIDInFavTeams) { if (isTeamIDInFavTeams) {
isFav = true isFav = true;
} }
} }
res.render('pages/clubs-page', { res.render("pages/clubs-page", {
isFav: isFav, isFav: isFav,
clubID: req.params.clubID, clubID: req.params.clubID,
clubs: res.locals.club clubs: res.locals.club,
}); });
}); });
@@ -158,24 +161,27 @@ app.get('/club/:clubID', [fetchClubsData], (req, res) => {
*************************/ *************************/
// Redirect to the /login endpoint // Redirect to the /login endpoint
app.get('/', (req, res) => { app.get("/", (req, res) => {
res.redirect('/home'); res.redirect("/home");
}); });
// Render login page for /login route // Render login page for /login route
app.get('/login', (req, res) => { app.get("/login", (req, res) => {
res.render('/'); res.render("/");
}); });
// Trigger login form to check database for matching username and password // Trigger login form to check database for matching username and password
app.post('/login', async (req, res) => { app.post("/login", async (req, res) => {
try { try {
// Check if username exists in DB // Check if username exists in DB
const user = await db.oneOrNone('SELECT * FROM users WHERE username = $1', req.body.username); const user = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
if (!user) { if (!user) {
// Redirect user to login screen if no user is found with the provided username // Redirect user to login screen if no user is found with the provided username
return res.redirect('/register'); return res.redirect("/register");
} }
// Check if password from request matches with password in DB // Check if password from request matches with password in DB
@@ -184,19 +190,18 @@ app.post('/login', async (req, res) => {
// Check if match returns no data // Check if match returns no data
if (!match) { if (!match) {
// Render the login page with the message parameter // Render the login page with the message parameter
return res.render('/', { message: 'Password does not match' }); return res.render("/", { message: "Password does not match" });
} } else {
else{
// Save user information in the session variable // Save user information in the session variable
req.session.user = user; req.session.user = user;
req.session.save(); req.session.save();
// Redirect user to the home page // Redirect user to the home page
res.redirect('/'); res.redirect("/");
} }
} catch (error) { } catch (error) {
// Direct user to login screen if no user is found with matching password // Direct user to login screen if no user is found with matching password
res.redirect('/register'); res.redirect("/register");
} }
}); });
@@ -205,38 +210,54 @@ app.post('/login', async (req, res) => {
*************************/ *************************/
// Render registration page for /register route // Render registration page for /register route
app.get('/register', (req, res) => { app.get("/register", (req, res) => {
res.redirect('/'); res.redirect("/");
}); });
// Trigger Registration Form to Post // Trigger Registration Form to Post
app.post('/register', async (req, res) => { app.post("/register", async (req, res) => {
try { try {
if (!req.body.username || !req.body.password) { if (!req.body.username || !req.body.password) {
// If username or password is missing, respond with status 400 and an error message // If username or password is missing, respond with status 400 and an error message
return res.status(400).json({ status: 'error', message: 'Invalid input' }); return res
.status(400)
.json({ status: "error", message: "Invalid input" });
} }
// Check if the username already exists in the database // Check if the username already exists in the database
const existingUser = await db.oneOrNone('SELECT * FROM users WHERE username = $1', req.body.username); const existingUser = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
if (existingUser) { if (existingUser) {
// If a user with the same username already exists, respond with status 409 and an error message // If a user with the same username already exists, respond with status 409 and an error message
return res.status(409).json({ status: 'error', message: 'Username already exists' }); return res
.status(409)
.json({ status: "error", message: "Username already exists" });
} }
// Hash the password using bcrypt library // Hash the password using bcrypt library
const hash = await bcrypt.hash(req.body.password, 10); const hash = await bcrypt.hash(req.body.password, 10);
// Insert username and hashed password into the 'users' table // Insert username and hashed password into the 'users' table
await db.none('INSERT INTO users (username, password) VALUES ($1, $2)', [req.body.username, hash]); await db.none("INSERT INTO users (username, password) VALUES ($1, $2)", [
const user = await db.oneOrNone('SELECT * FROM users WHERE username = $1', req.body.username); req.body.username,
hash,
]);
const user = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
req.session.user = user; req.session.user = user;
req.session.save(); req.session.save();
// Redirect user to the home page // Redirect user to the home page
res.redirect('/home'); res.redirect("/home");
} catch (error) { } catch (error) {
// If an error occurs during registration, respond with status 500 and an error message // If an error occurs during registration, respond with status 500 and an error message
res.status(500).json({ status: 'error', message: 'An error occurred during registration' }); res.status(500).json({
status: "error",
message: "An error occurred during registration",
});
} }
}); });
@@ -244,19 +265,19 @@ app.post('/register', async (req, res) => {
Home Page Routes Home Page Routes
*************************/ *************************/
app.get('/home', (req, res) => { app.get("/home", (req, res) => {
const loggedIn = req.session.user ? true : false; const loggedIn = req.session.user ? true : false;
res.render('pages/home'); res.render("pages/home");
}); });
app.get('/logout', (req, res) => { app.get("/logout", (req, res) => {
req.session.destroy(err => { req.session.destroy((err) => {
if (err) { if (err) {
console.error('Error destroying session:', err); console.error("Error destroying session:", err);
res.status(500).send('Internal Server Error'); res.status(500).send("Internal Server Error");
} else { } else {
// Redirect to the same page after destroying the session // Redirect to the same page after destroying the session
res.redirect('/'); // You can change '/' to the desired page if it's not the home page res.redirect("/"); // You can change '/' to the desired page if it's not the home page
} }
}); });
}); });
@@ -266,7 +287,7 @@ app.get('/logout', (req, res) => {
*************************/ *************************/
// Import and call generateLeagueRoutes function // Import and call generateLeagueRoutes function
const generateLeagueRoutes = require('./src/assets/routes/league-pages/generate-league-routes'); const generateLeagueRoutes = require("./src/assets/routes/league-pages/generate-league-routes");
generateLeagueRoutes(app); generateLeagueRoutes(app);
/************************ /************************
@@ -274,7 +295,7 @@ generateLeagueRoutes(app);
*************************/ *************************/
// Import and call generateLeagueRoutes function // Import and call generateLeagueRoutes function
const generateClubRoutes = require('./src/assets/routes/club-pages/generate-club-routes'); const generateClubRoutes = require("./src/assets/routes/club-pages/generate-club-routes");
generateClubRoutes(app); generateClubRoutes(app);
/************************ /************************
@@ -284,78 +305,94 @@ generateClubRoutes(app);
// Function to add a new row to the FavoriteTeams table // Function to add a new row to the FavoriteTeams table
// database configuration // database configuration
app.post('/favteam/add', async (req, res, next) => { app.post("/favteam/add", async (req, res, next) => {
try { try {
const { userID, teamID, teamName, teamLogo } = req.body; const { userID, teamID, teamName, teamLogo } = req.body;
// Check if the user is logged in // Check if the user is logged in
if (!req.session.user) { if (!req.session.user) {
return res.status(400).json({ message: 'Login or register to add a favorite team.' }); return res
.status(400)
.json({ message: "Login or register to add a favorite team." });
} }
// Insert the new favorite team into the database // Insert the new favorite team into the database
const query = { const query = {
text: 'INSERT INTO FavoriteTeams (UserID, TeamID, TeamName, TeamLogo) VALUES ($1, $2, $3, $4)', text: "INSERT INTO FavoriteTeams (UserID, TeamID, TeamName, TeamLogo) VALUES ($1, $2, $3, $4)",
values: [userID, teamID, teamName, teamLogo], values: [userID, teamID, teamName, teamLogo],
}; };
await db.none(query); await db.none(query);
console.log('New favorite team added successfully.'); console.log("New favorite team added successfully.");
return res.status(200).json({ message: 'New favorite team added successfully.' }); return res
.status(200)
.json({ message: "New favorite team added successfully." });
} catch (error) { } catch (error) {
console.error('Error adding favorite team:', error); console.error("Error adding favorite team:", error);
return res.status(500).json({ error: 'Error adding favorite team' }); return res.status(500).json({ error: "Error adding favorite team" });
} }
}); });
app.post('/favteam/remove', async (req, res) => { app.post("/favteam/remove", async (req, res) => {
try { try {
const { userID, teamID } = req.body; const { userID, teamID } = req.body;
// Check if the team exists for the user // Check if the team exists for the user
const existingTeam = await db.oneOrNone( const existingTeam = await db.oneOrNone(
'SELECT * FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2', "SELECT * FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID] [userID, teamID]
); );
// If the team does not exist for the user, return a 404 error // If the team does not exist for the user, return a 404 error
if (!existingTeam) { if (!existingTeam) {
return res.status(404).json({ message: 'This team is not in your favorites.' }); return res
.status(404)
.json({ message: "This team is not in your favorites." });
} }
// Remove the favorite team from the database // Remove the favorite team from the database
await db.none( await db.none(
'DELETE FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2', "DELETE FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID] [userID, teamID]
); );
console.log('Favorite team removed successfully.'); console.log("Favorite team removed successfully.");
return res.status(200).json({ message: 'Favorite team removed successfully.' }); return res
.status(200)
.json({ message: "Favorite team removed successfully." });
} catch (error) { } catch (error) {
console.error('Error removing favorite team:', error); console.error("Error removing favorite team:", error);
// If the error is a database error, return a 500 error // If the error is a database error, return a 500 error
if (error instanceof QueryResultError) { if (error instanceof QueryResultError) {
return res.status(500).json({ error: 'Database error occurred while removing favorite team' }); return res.status(500).json({
error: "Database error occurred while removing favorite team",
});
} }
// If the error is a generic error, return a 400 error // If the error is a generic error, return a 400 error
return res.status(400).json({ error: 'Error occurred while removing favorite team' }); return res
.status(400)
.json({ error: "Error occurred while removing favorite team" });
} }
}); });
async function getFavoriteTeamsForUser(userId) { async function getFavoriteTeamsForUser(userId) {
try { try {
// Execute the SQL query // Execute the SQL query
const favoriteTeams = await db.any(` const favoriteTeams = await db.any(
`
SELECT * FROM FavoriteTeams SELECT * FROM FavoriteTeams
WHERE UserID = $1; WHERE UserID = $1;
`, userId);`a` `,
userId
);
`a`;
// Return the result // Return the result
return favoriteTeams; return favoriteTeams;
} catch (error) { } catch (error) {
console.error('Error fetching favorite teams:', error); console.error("Error fetching favorite teams:", error);
throw error; // Rethrow the error for handling at a higher level throw error; // Rethrow the error for handling at a higher level
} }
} }
@@ -365,4 +402,4 @@ async function getFavoriteTeamsForUser(userId) {
// ***************************************************** // *****************************************************
// starting the server and keeping the connection open to listen for more requests // starting the server and keeping the connection open to listen for more requests
module.exports = app.listen(3000); module.exports = app.listen(3000);
console.log('Server is listening on port 3000'); console.log("Server is listening on port 3000");

View File

@@ -1,35 +1,20 @@
/* Main Contents Container (Below Header) */ /* Main Contents Container (Below Header) */
#club-page-contents-container #club-page-contents-container {
{
display: flex; display: flex;
flex-direction: row; flex-direction: row;
} }
/* Child Containers */ /* Child Containers */
/* Left 20% of #club-page-contents-container */ /* Left 20% of #club-page-contents-container */
#club-information-container #club-information-container {
{
width: 20%; width: 20%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
/* Right 80% of #club-page-contents-container */ /* Right 80% of #club-page-contents-container */
#club-stats-and-players-container #club-stats-and-players-container {
{
width: 80%; width: 80%;
} }

View File

@@ -1,10 +1,8 @@
#club-information-container #club-information-container {
{
margin-right: 20px; margin-right: 20px;
} }
#club-favorite-button #club-favorite-button {
{
width: 35px; width: 35px;
transform: skewX(20deg); transform: skewX(20deg);
margin-right: 25px; margin-right: 25px;
@@ -12,8 +10,7 @@
filter: outline(2px solid red); filter: outline(2px solid red);
} }
#club-favorite-button:hover #club-favorite-button:hover {
{
cursor: pointer; cursor: pointer;
} }

View File

@@ -26,8 +26,7 @@
*/ */
/* Stylization for League Information Header Card */ /* Stylization for League Information Header Card */
.information-container .information-container {
{
/* --- POSITION CONTAINER --- */ /* --- POSITION CONTAINER --- */
align-items: center; /* Center content vertically */ align-items: center; /* Center content vertically */
margin: 20px; margin: 20px;
@@ -38,7 +37,12 @@
padding: 10px 20px; /* Adjust padding as needed */ padding: 10px 20px; /* Adjust padding as needed */
/* --- STYLE CONTAINER --- */ /* --- STYLE CONTAINER --- */
background: linear-gradient(to right, white, rgb(245, 245, 245), rgb(227, 227, 227)); /* Gradient from white to gray */ background: linear-gradient(
to right,
white,
rgb(245, 245, 245),
rgb(227, 227, 227)
); /* Gradient from white to gray */
transform: skewX(-20deg); /* Skew the banner to create a triangular side */ transform: skewX(-20deg); /* Skew the banner to create a triangular side */
box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.4); box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.4);
@@ -48,9 +52,8 @@
} }
/* Adds Red Diagonal Strip at the end of the #league-information-container */ /* Adds Red Diagonal Strip at the end of the #league-information-container */
.information-container::after .information-container::after {
{ content: "";
content: '';
position: absolute; position: absolute;
top: 0; top: 0;
right: 0; right: 0;
@@ -59,34 +62,31 @@
background-color: red; /* Red color */ background-color: red; /* Red color */
} }
/* /*
=========================== ===========================
LEAGUE INFORMATION CHILD ITEMS LEAGUE INFORMATION CHILD ITEMS
=========================== ===========================
*/ */
/* Styling for League Logo in League Information Header */ /* Styling for League Logo in League Information Header */
#generated-page-header-logo #generated-page-header-logo {
{
margin: 0px 30px; margin: 0px 30px;
transform: skewX(20deg); /* Skew the banner to create a triangular side */ transform: skewX(20deg); /* Skew the banner to create a triangular side */
height: 80%; height: 80%;
} }
/* Styling for League Title in League Information Header */ /* Styling for League Title in League Information Header */
#generated-page-header-title #generated-page-header-title {
{
transform: skewX(20deg); /* Skew the banner to create a triangular side */ transform: skewX(20deg); /* Skew the banner to create a triangular side */
margin-right: 20px; margin-right: 20px;
} }
/* Styling for Flag in League Information Header */ /* Styling for Flag in League Information Header */
#generated-page-header-flag #generated-page-header-flag {
{
transform: skewX(20deg); /* Skew the banner to create a triangular side */ transform: skewX(20deg); /* Skew the banner to create a triangular side */
height: 20px; height: 20px;
margin-right: 130px; margin-right: 130px;
} }
/* /*
============================================= =============================================
@@ -95,8 +95,7 @@
*/ */
/* Styling for All Card Containers on Generated Pages */ /* Styling for All Card Containers on Generated Pages */
.card-container .card-container {
{
/* --- POSITION CONTAINER --- */ /* --- POSITION CONTAINER --- */
margin: 0 10px; margin: 0 10px;
margin-bottom: 20px; margin-bottom: 20px;
@@ -105,33 +104,34 @@
padding: 15px; padding: 15px;
/* --- STYLE CONTAINER --- */ /* --- STYLE CONTAINER --- */
background: linear-gradient(to top, rgb(216, 216, 216), rgb(236, 236, 236), rgb(241, 240, 240)); background: linear-gradient(
to top,
rgb(216, 216, 216),
rgb(236, 236, 236),
rgb(241, 240, 240)
);
border: 1px solid gray; border: 1px solid gray;
box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.5); box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.5);
} }
/* Styling for All Tables on Generated Pages */ /* Styling for All Tables on Generated Pages */
table table {
{
width: 100%; width: 100%;
padding: 15px; padding: 15px;
/* Table Header Styling */ /* Table Header Styling */
th th {
{
border-bottom: 3px solid red; /* Add red bottom border */ border-bottom: 3px solid red; /* Add red bottom border */
} }
/* Data in Row Style */ /* Data in Row Style */
td td {
{
padding: 5px; padding: 5px;
} }
} }
/* Styling for All Tables Designated to Alternate on Generated Pages */ /* Styling for All Tables Designated to Alternate on Generated Pages */
.alternating-table tbody tr:nth-child(odd) .alternating-table tbody tr:nth-child(odd) {
{
/* Every Odd Row in Table Style */ /* Every Odd Row in Table Style */
background-color: #d2d2d2; /* Light gray for odd rows */ background-color: #d2d2d2; /* Light gray for odd rows */
} }
@@ -143,28 +143,24 @@ table
*/ */
/* Hover Styling for All Card Containers on Generated Pages */ /* Hover Styling for All Card Containers on Generated Pages */
.card-container:hover .card-container:hover {
{
transform: scale(1.01); /* Scale the row by 1.1 on hover */ transform: scale(1.01); /* Scale the row by 1.1 on hover */
box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.3); box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.3);
} }
/* Hover Styling for All Tables Designated to Alternate on Generated Pages */ /* Hover Styling for All Tables Designated to Alternate on Generated Pages */
.alternating-table tbody tr:hover .alternating-table tbody tr:hover {
{
/* Create border around row on hover */ /* Create border around row on hover */
border: 1px solid lightgray; border: 1px solid lightgray;
border-radius: 10px; border-radius: 10px;
/* Make club logo larger on hover */ /* Make club logo larger on hover */
#league-table-club-logo #league-table-club-logo {
{
width: 32px; width: 32px;
} }
/* Undeline club name on hover */ /* Undeline club name on hover */
#league-table-club-name-column #league-table-club-name-column {
{
text-decoration: underline; /* Add underline effect */ text-decoration: underline; /* Add underline effect */
} }
} }

View File

@@ -6,7 +6,7 @@
/* Styling for text at top of the page */ /* Styling for text at top of the page */
#leagues-header { #leagues-header {
font-family: 'Scottsdale-Italic'; font-family: "Scottsdale-Italic";
display: inline-block; /* Ensure the width is based on content */ display: inline-block; /* Ensure the width is based on content */
border-bottom: 1.5px solid #999696; /* Adjust the color and thickness as needed */ border-bottom: 1.5px solid #999696; /* Adjust the color and thickness as needed */
} }
@@ -24,7 +24,12 @@
height: 150px; height: 150px;
margin: 20px; margin: 20px;
text-align: center; /* Center the content horizontally */ text-align: center; /* Center the content horizontally */
background: linear-gradient(to right, white, rgb(245, 245, 245), rgb(227, 227, 227)); /* Gradient from white to gray */ background: linear-gradient(
to right,
white,
rgb(245, 245, 245),
rgb(227, 227, 227)
); /* Gradient from white to gray */
padding: 10px; /* Adjust padding as needed */ padding: 10px; /* Adjust padding as needed */
position: relative; /* Needed for absolute positioning */ position: relative; /* Needed for absolute positioning */
overflow: hidden; /* Hide the overflowing skewed content */ overflow: hidden; /* Hide the overflowing skewed content */
@@ -45,14 +50,13 @@
transform: skewX(20deg); /* Skew the banner to create a triangular side */ transform: skewX(20deg); /* Skew the banner to create a triangular side */
} }
#league-card:hover { #league-card:hover {
transform: skewX(-20deg) scale(1.05); /* Increase scale on hover to make it pop */ transform: skewX(-20deg) scale(1.05); /* Increase scale on hover to make it pop */
box-shadow: 0 0 20px rgba(0, 0, 0, 0.3); /* Add box-shadow on hover for depth effect */ box-shadow: 0 0 20px rgba(0, 0, 0, 0.3); /* Add box-shadow on hover for depth effect */
} }
#league-card::after { #league-card::after {
content: ''; content: "";
position: absolute; position: absolute;
top: 0; top: 0;
right: 0; right: 0;
@@ -61,7 +65,6 @@
background-color: red; /* Red color */ background-color: red; /* Red color */
} }
#logo { #logo {
width: 30%; /* Set width for logo */ width: 30%; /* Set width for logo */
max-height: 100px; max-height: 100px;
@@ -77,5 +80,3 @@
max-height: 80px; max-height: 80px;
max-width: 250px; max-width: 250px;
} }

View File

@@ -1,7 +1,7 @@
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function () {
var favoriteButton = document.getElementById("club-favorite-button"); var favoriteButton = document.getElementById("club-favorite-button");
if (favoriteButton) { if (favoriteButton) {
favoriteButton.addEventListener("click", function() { favoriteButton.addEventListener("click", function () {
var userID = document.getElementById("userID").value; var userID = document.getElementById("userID").value;
var teamID = document.getElementById("teamID").value; var teamID = document.getElementById("teamID").value;
var teamName = document.getElementById("teamName").value; var teamName = document.getElementById("teamName").value;
@@ -16,58 +16,56 @@ document.addEventListener("DOMContentLoaded", function() {
} }
}); });
async function addFavoriteTeam(userID, teamID, teamName, teamLogo){ async function addFavoriteTeam(userID, teamID, teamName, teamLogo) {
try { try {
const response = await fetch('/favteam/add', { const response = await fetch("/favteam/add", {
method: 'POST', method: "POST",
headers: { headers: {
'Content-Type': 'application/json' "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
userID: userID, userID: userID,
teamID: teamID, teamID: teamID,
teamName: teamName, teamName: teamName,
teamLogo: teamLogo teamLogo: teamLogo,
}) }),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error('Failed to add favorite team'); throw new Error("Failed to add favorite team");
} }
if (response.status === 200) { if (response.status === 200) {
console.log('New favorite team added successfully.'); console.log("New favorite team added successfully.");
var favoriteButton = document.getElementById("club-favorite-button"); var favoriteButton = document.getElementById("club-favorite-button");
favoriteButton.src = "/img/club-page/favorited.png"; favoriteButton.src = "/img/club-page/favorited.png";
location.reload(); // Refresh the page location.reload(); // Refresh the page
} }
} catch (error) { } catch (error) {
console.error('Error adding favorite team:', error); console.error("Error adding favorite team:", error);
} }
} }
async function removeFavoriteTeam(userID, teamID) { async function removeFavoriteTeam(userID, teamID) {
try { try {
const response = await fetch('/favteam/remove', { const response = await fetch("/favteam/remove", {
method: 'POST', method: "POST",
headers: { headers: {
'Content-Type': 'application/json' "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
userID: userID, userID: userID,
teamID: teamID teamID: teamID,
}) }),
}); });
if (response.status === 200) { if (response.status === 200) {
console.log('Favorite team removed successfully.'); console.log("Favorite team removed successfully.");
var favoriteButton = document.getElementById("club-favorite-button"); var favoriteButton = document.getElementById("club-favorite-button");
favoriteButton.src = "/img/club-page/unfavorited.png"; favoriteButton.src = "/img/club-page/unfavorited.png";
location.reload(); // Refresh the page location.reload(); // Refresh the page
} }
} catch (error) { } catch (error) {
console.error('Error removing favorite team:', error); console.error("Error removing favorite team:", error);
} }
} }

View File

@@ -1,26 +1,23 @@
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function () {
var goalDifferenceCells = document.querySelectorAll("#league-table-goal-difference-column"); // Selecting the cells in the goal_difference column var goalDifferenceCells = document.querySelectorAll(
"#league-table-goal-difference-column"
); // Selecting the cells in the goal_difference column
goalDifferenceCells.forEach(function(cell) { goalDifferenceCells.forEach(function (cell) {
var goalDifference = parseInt(cell.textContent); var goalDifference = parseInt(cell.textContent);
var color; var color;
if (goalDifference < 0) if (goalDifference < 0) {
{
// Gradually darken the text color for negative goal differences // Gradually darken the text color for negative goal differences
var darkenFactor = Math.ceil(goalDifference / -10); // Calculate the darken factor var darkenFactor = Math.ceil(goalDifference / -10); // Calculate the darken factor
var shade = Math.max(0, 255 - darkenFactor * 25); // Calculate the shade of red var shade = Math.max(0, 255 - darkenFactor * 25); // Calculate the shade of red
color = "rgb(" + shade + ", 0, 0)"; // Create the color value color = "rgb(" + shade + ", 0, 0)"; // Create the color value
} } else if (goalDifference > 0) {
else if (goalDifference > 0)
{
// Gradually darken the text color for positive goal differences // Gradually darken the text color for positive goal differences
var darkenFactor = Math.floor(goalDifference / 10); // Calculate the darken factor var darkenFactor = Math.floor(goalDifference / 10); // Calculate the darken factor
var shade = Math.max(0, 155 - darkenFactor * 15); // Adjusted the starting point to make greens darker var shade = Math.max(0, 155 - darkenFactor * 15); // Adjusted the starting point to make greens darker
color = "rgb(0, " + shade + ", 0)"; // Create the color value color = "rgb(0, " + shade + ", 0)"; // Create the color value
} } else {
else
{
color = "inherit"; // If goal difference is 0, leave text color unchanged color = "inherit"; // If goal difference is 0, leave text color unchanged
} }

View File

@@ -20,7 +20,7 @@ function makeNavbarSticky() {
// Adjust the position of the account pane // Adjust the position of the account pane
accountPane.style.position = "fixed"; // Make the account pane fixed accountPane.style.position = "fixed"; // Make the account pane fixed
accountPane.style.top = navbar.offsetHeight + 20 + 'px'; // Move the account pane below the navbar accountPane.style.top = navbar.offsetHeight + 20 + "px"; // Move the account pane below the navbar
} else { } else {
// Remove the 'fixed-top' class to make the navbar non-sticky // Remove the 'fixed-top' class to make the navbar non-sticky
navbar.classList.remove("fixed-top"); navbar.classList.remove("fixed-top");
@@ -34,12 +34,12 @@ function makeNavbarSticky() {
} }
// Call the stickyNavbar function when the page is scrolled // Call the stickyNavbar function when the page is scrolled
window.onscroll = function() { window.onscroll = function () {
stickyNavbar(); stickyNavbar();
}; };
} }
// Call the makeNavbarSticky function when the page loads // Call the makeNavbarSticky function when the page loads
window.onload = function() { window.onload = function () {
makeNavbarSticky(); makeNavbarSticky();
}; };

View File

@@ -1,7 +1,9 @@
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function () {
var deleteButtons = document.querySelectorAll("#account-delete-favorite-team-button-hover"); var deleteButtons = document.querySelectorAll(
deleteButtons.forEach(function(deleteButton) { "#account-delete-favorite-team-button-hover"
deleteButton.addEventListener("click", function() { );
deleteButtons.forEach(function (deleteButton) {
deleteButton.addEventListener("click", function () {
var userID = deleteButton.getAttribute("userID"); var userID = deleteButton.getAttribute("userID");
var teamID = deleteButton.getAttribute("teamID"); var teamID = deleteButton.getAttribute("teamID");
@@ -14,23 +16,22 @@ document.addEventListener("DOMContentLoaded", function() {
async function removeAccountFavoriteTeam(userID, teamID) { async function removeAccountFavoriteTeam(userID, teamID) {
try { try {
const response = await fetch('/favteam/remove', { const response = await fetch("/favteam/remove", {
method: 'POST', method: "POST",
headers: { headers: {
'Content-Type': 'application/json' "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
userID: userID, userID: userID,
teamID: teamID teamID: teamID,
}) }),
}); });
if (response.status === 200) { if (response.status === 200) {
console.log('Favorite team removed successfully.'); console.log("Favorite team removed successfully.");
location.reload(); // Refresh the page location.reload(); // Refresh the page
} }
} catch (error) { } catch (error) {
console.error('Error removing favorite team:', error); console.error("Error removing favorite team:", error);
} }
} }

View File

@@ -1,41 +1,34 @@
$(document).ready(function() { $(document).ready(function () {
// When #user is clicked // When #user is clicked
$('#user-profile-button').click(function() { $("#user-profile-button").click(function () {
$("#register-screen-container").hide();
$('#register-screen-container').hide();
// Toggle the visibility of the login container // Toggle the visibility of the login container
$('#login-pane').toggle(); $("#login-pane").toggle();
}); });
$('#register-page-login-button').click(function (event) { $("#register-page-login-button").click(function (event) {
event.preventDefault(); // Prevent the default action of following the link event.preventDefault(); // Prevent the default action of following the link
$('#register-screen-container').hide(); $("#register-screen-container").hide();
$('#login-pane').show(); $("#login-pane").show();
}); });
}); });
$(document).ready(function () { $(document).ready(function () {
// Listen for click event on the register button // Listen for click event on the register button
$('#register-button').click(function (event) { $("#register-button").click(function (event) {
event.preventDefault(); // Prevent the default action of following the link event.preventDefault(); // Prevent the default action of following the link
$('#login-pane').hide(); $("#login-pane").hide();
// Show the register container // Show the register container
$('#register-screen-container').show(); $("#register-screen-container").show();
}); });
}); });
$(document).ready(function() { $(document).ready(function () {
// When #user is clicked // When #user is clicked
$('#user-profile-button').click(function() { $("#user-profile-button").click(function () {
// Toggle the visibility of the login container // Toggle the visibility of the login container
$('#account-pane').toggle(); $("#account-pane").toggle();
}); });
}); });

View File

@@ -1,4 +1,4 @@
const axios = require('axios'); const axios = require("axios");
// Middleware function to fetch clubs data // Middleware function to fetch clubs data
const fetchClubsData = async (req, res, next) => { const fetchClubsData = async (req, res, next) => {
@@ -7,11 +7,14 @@ const fetchClubsData = async (req, res, next) => {
const clubID = req.params.clubID; const clubID = req.params.clubID;
// Make GET request to the API endpoint using the club ID // Make GET request to the API endpoint using the club ID
const response = await axios.get(`http://api.football-data.org/v4/teams/${clubID}/?offset=&limit=`, { const response = await axios.get(
`http://api.football-data.org/v4/teams/${clubID}/?offset=&limit=`,
{
headers: { headers: {
'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', // Add your API key here "X-Auth-Token": "0aa1ed31245d4a36b1ef5a79150324b3", // Add your API key here
}, },
}); }
);
// Extract relevant data from the API response // Extract relevant data from the API response
const clubData = response.data; const clubData = response.data;
@@ -34,12 +37,12 @@ const fetchClubsData = async (req, res, next) => {
founded: clubData.founded, founded: clubData.founded,
clubColors: clubData.clubColors, clubColors: clubData.clubColors,
venue: clubData.venue, venue: clubData.venue,
runningCompetitions: clubData.runningCompetitions.map(competition => ({ runningCompetitions: clubData.runningCompetitions.map((competition) => ({
id: competition.id, id: competition.id,
name: competition.name, name: competition.name,
code: competition.code, code: competition.code,
type: competition.type, type: competition.type,
emblem: competition.emblem emblem: competition.emblem,
})), })),
coach: { coach: {
id: clubData.coach.id, id: clubData.coach.id,
@@ -50,22 +53,22 @@ const fetchClubsData = async (req, res, next) => {
nationality: clubData.coach.nationality, nationality: clubData.coach.nationality,
contract: { contract: {
start: clubData.coach.contract.start, start: clubData.coach.contract.start,
until: clubData.coach.contract.until until: clubData.coach.contract.until,
}
}, },
squad: clubData.squad.map(player => ({ },
squad: clubData.squad.map((player) => ({
id: player.id, id: player.id,
name: player.name, name: player.name,
position: player.position, position: player.position,
dateOfBirth: player.dateOfBirth, dateOfBirth: player.dateOfBirth,
nationality: player.nationality nationality: player.nationality,
})), })),
staff: clubData.staff, staff: clubData.staff,
lastUpdated: clubData.lastUpdated lastUpdated: clubData.lastUpdated,
}; };
next(); next();
} catch (error) { } catch (error) {
console.error('Error fetching clubs data:', error); console.error("Error fetching clubs data:", error);
res.locals.club = null; // Set to null if there's an error res.locals.club = null; // Set to null if there's an error
next(); // Call next middleware or route handler next(); // Call next middleware or route handler
} }

View File

@@ -1,4 +1,4 @@
const express = require('express'); const express = require("express");
const app = express(); const app = express();
// generate-league-routes.js // generate-league-routes.js
@@ -6,12 +6,10 @@ const app = express();
// Define a function to generate league routes // Define a function to generate league routes
module.exports = function generateClubRoutes(app) { module.exports = function generateClubRoutes(app) {
// Define a route to handle requests to "/league/:leagueName" // Define a route to handle requests to "/league/:leagueName"
app.get('/club/:clubID', (req, res) => { app.get("/club/:clubID", (req, res) => {
// Extract the league name from the URL parameters // Extract the league name from the URL parameters
const clubID = req.params.clubID; const clubID = req.params.clubID;
// Render the league page template using Handlebars // Render the league page template using Handlebars
res.render('pages/club-page', { clubID: clubID, }); res.render("pages/club-page", { clubID: clubID });
}); });
}; };

View File

@@ -1,11 +1,15 @@
// Add click event listener to club logos // Add click event listener to club logos
document.querySelectorAll('#league-table-club-logo, #league-table-club-name-column, #league-top-scorers-logo, #league-top-scorers-club-name-column').forEach(element => { document
element.addEventListener('click', (event) => { .querySelectorAll(
"#league-table-club-logo, #league-table-club-name-column, #league-top-scorers-logo, #league-top-scorers-club-name-column"
)
.forEach((element) => {
element.addEventListener("click", (event) => {
// Get the club ID from the clicked club logo's clubID attribute // Get the club ID from the clicked club logo's clubID attribute
const clubId = element.getAttribute('clubID'); const clubId = element.getAttribute("clubID");
redirectToClubPage(clubId); redirectToClubPage(clubId);
}); });
}); });
// Function to redirect to the club page // Function to redirect to the club page
function redirectToClubPage(clubID) { function redirectToClubPage(clubID) {

View File

@@ -1,4 +1,4 @@
const express = require('express'); const express = require("express");
const app = express(); const app = express();
// generate-league-routes.js // generate-league-routes.js
@@ -6,12 +6,10 @@ const app = express();
// Define a function to generate league routes // Define a function to generate league routes
module.exports = function generateLeagueRoutes(app) { module.exports = function generateLeagueRoutes(app) {
// Define a route to handle requests to "/league/:leagueName" // Define a route to handle requests to "/league/:leagueName"
app.get('/league/:leagueID', (req, res) => { app.get("/league/:leagueID", (req, res) => {
// Extract the league name from the URL parameters // Extract the league name from the URL parameters
const leagueID = req.params.leagueID; const leagueID = req.params.leagueID;
// Render the league page template using Handlebars // Render the league page template using Handlebars
res.render('pages/leagues-page', { leagueID: leagueID, user: user}); res.render("pages/leagues-page", { leagueID: leagueID, user: user });
}); });
}; };

View File

@@ -1,19 +1,19 @@
const axios = require('axios'); const axios = require("axios");
const fetchTeamNames = async (selectedLeague) => { const fetchTeamNames = async (selectedLeague) => {
try { try {
const response = await axios({ const response = await axios({
url: `http://api.football-data.org/v4/competitions/${selectedLeague}/teams`, url: `http://api.football-data.org/v4/competitions/${selectedLeague}/teams`,
method: 'GET', method: "GET",
headers: { headers: {
'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', "X-Auth-Token": "0aa1ed31245d4a36b1ef5a79150324b3",
}, },
}); });
const teams = response.data.teams.map(team => team.name); const teams = response.data.teams.map((team) => team.name);
return teams; return teams;
} catch (error) { } catch (error) {
console.error('Error fetching teams data:', error); console.error("Error fetching teams data:", error);
return []; return [];
} }
}; };

View File

@@ -1,6 +1,8 @@
<!-- Linking forms.css --> <!-- Linking forms.css -->
<div class="account-portal-container" id="login-pane"> <div class="account-portal-container" id="login-pane">
<div class="form-container" id="login-form"> <div class="form-container" id="login-form">
<img id="account-portal-logo" src="/img/logo.png" style="width: 150px;">
<h1 class="mt-5 mb-4">Login</h1> <h1 class="mt-5 mb-4">Login</h1>
<!-- Check if message variable is present to display message partial --> <!-- Check if message variable is present to display message partial -->