From d22576cf0b25be27a37ce3dad54e0de81095427c Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Mon, 14 Jul 2025 13:29:55 -0400 Subject: [PATCH 01/38] Poll Table --- .env.example | 3 --- database/db.js | 2 +- database/poll.js | 50 +++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 4 ++-- 4 files changed, 53 insertions(+), 6 deletions(-) delete mode 100644 .env.example create mode 100644 database/poll.js diff --git a/.env.example b/.env.example deleted file mode 100644 index 848ad61..0000000 --- a/.env.example +++ /dev/null @@ -1,3 +0,0 @@ -DATABASE_URL=postgres://hostname:5432/database-name -JWT_SECRET=super-secret-jwt-key -FRONTEND_URL=http://localhost:3000 diff --git a/database/db.js b/database/db.js index b251a9d..42ae341 100644 --- a/database/db.js +++ b/database/db.js @@ -3,7 +3,7 @@ const { Sequelize } = require("sequelize"); const pg = require("pg"); // Feel free to rename the database to whatever you want! -const dbName = "capstone-1"; +const dbName = "Capstone1"; const db = new Sequelize( process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`, diff --git a/database/poll.js b/database/poll.js new file mode 100644 index 0000000..1ad17e1 --- /dev/null +++ b/database/poll.js @@ -0,0 +1,50 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); +const { DESCRIBE } = require("sequelize/lib/query-types"); + + +const Polls = db.define ("polls" , + { + id: + { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + user_id: + { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + title: + { + type: DataTypes.VARCHAR, + allowNull: false, + }, + Description: + { + type: DataTypes.TEXT, + allowNull: true, + }, + isActive: + { + type: DataTypes.BOOLEAN + }, + createdAt: + { + type: DataTypes.DATE + } + }) + + +// Table polls { +// id int [pk, increment] +// user_id int [ref: > users.id] +// title varchar [not null] +// description text +// is_active boolean [default: true] +// created_at datetime +// } + +module.exports = Polls; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index af0cf82..1b30289 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "capstone-i-backend", + "name": "capstone-1-backend", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "capstone-i-backend", + "name": "capstone-1-backend", "version": "1.0.0", "license": "ISC", "dependencies": { From 201184de0479c1be04ab63bb8d66587ef59c58df Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Mon, 14 Jul 2025 14:53:17 -0400 Subject: [PATCH 02/38] seeded database and created router.get for polls --- api/index.js | 3 +++ api/poll.js | 15 ++++++++++++++ database/Polls.js | 34 ++++++++++++++++++++++++++++++++ database/index.js | 3 +++ database/poll.js | 50 ----------------------------------------------- database/seed.js | 27 +++++++++++++++++++++---- 6 files changed, 78 insertions(+), 54 deletions(-) create mode 100644 api/poll.js create mode 100644 database/Polls.js delete mode 100644 database/poll.js diff --git a/api/index.js b/api/index.js index f08162e..eb55059 100644 --- a/api/index.js +++ b/api/index.js @@ -1,6 +1,9 @@ const express = require("express"); const router = express.Router(); const testDbRouter = require("./test-db"); +// const usersRouter = require("./user"); +const pollsRouter = require("./poll"); +router.use("/Polls", pollsRouter); router.use("/test-db", testDbRouter); diff --git a/api/poll.js b/api/poll.js new file mode 100644 index 0000000..02868cb --- /dev/null +++ b/api/poll.js @@ -0,0 +1,15 @@ +const express = require("express"); +const router = express.Router(); +const { Polls } = require("../database"); + +router.get("/", async (req, res) => { + try { + const polls = await Polls.findAll(); + res.status(200).send(polls); + } catch (error) { + console.error(error); + res.status(500).json({ error: "Failed to fetch polls" }); + } +}); + +module.exports = router; diff --git a/database/Polls.js b/database/Polls.js new file mode 100644 index 0000000..63737d2 --- /dev/null +++ b/database/Polls.js @@ -0,0 +1,34 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); + +const Polls = db.define("polls", { + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + user_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { + model: "users", + key: "id", + }, + }, + title: { + type: DataTypes.STRING, + allowNull: false, + }, + description: { + type: DataTypes.TEXT, + allowNull: true, + }, + isActive: { + type: DataTypes.BOOLEAN, + defaultValue: true, + }, +}, { + timestamps: true, +}); + +module.exports = Polls; diff --git a/database/index.js b/database/index.js index e498df6..22744a9 100644 --- a/database/index.js +++ b/database/index.js @@ -1,7 +1,10 @@ const db = require("./db"); const User = require("./user"); +const Polls = require("./Polls"); module.exports = { db, User, + Polls, }; + diff --git a/database/poll.js b/database/poll.js deleted file mode 100644 index 1ad17e1..0000000 --- a/database/poll.js +++ /dev/null @@ -1,50 +0,0 @@ -const { DataTypes } = require("sequelize"); -const db = require("./db"); -const { DESCRIBE } = require("sequelize/lib/query-types"); - - -const Polls = db.define ("polls" , - { - id: - { - type: DataTypes.INTEGER, - autoIncrement: true, - primaryKey: true, - }, - user_id: - { - type: DataTypes.INTEGER, - autoIncrement: true, - primaryKey: true, - }, - title: - { - type: DataTypes.VARCHAR, - allowNull: false, - }, - Description: - { - type: DataTypes.TEXT, - allowNull: true, - }, - isActive: - { - type: DataTypes.BOOLEAN - }, - createdAt: - { - type: DataTypes.DATE - } - }) - - -// Table polls { -// id int [pk, increment] -// user_id int [ref: > users.id] -// title varchar [not null] -// description text -// is_active boolean [default: true] -// created_at datetime -// } - -module.exports = Polls; \ No newline at end of file diff --git a/database/seed.js b/database/seed.js index e58b595..5622e00 100644 --- a/database/seed.js +++ b/database/seed.js @@ -1,5 +1,6 @@ const db = require("./db"); const { User } = require("./index"); +const { Polls } = require("./index.js") const seed = async () => { try { @@ -12,10 +13,28 @@ const seed = async () => { { username: "user2", passwordHash: User.hashPassword("user222") }, ]); - console.log(`šŸ‘¤ Created ${users.length} users`); - - // Create more seed data here once you've created your models - // Seed files are a great way to test your database schema! + const polls = await Polls.bulkCreate([ + { + user_id: users[0].id, + title: "What is your favorite programming language?", + description: "Vote for the language you love the most!", + isActive: true, + }, + { + user_id: users[1].id, + title: "Do you prefer remote or inperson work?", + description: "Let us settle this once and for all.", + isActive: true, + }, + { + user_id: users[2].id, + title: "Whats your favorite resturant?", + description: "Vote yes or no for an offsite trip.", + isActive: false, + }, + ]); + + console.log(`šŸ‘¤ Created ${users.length} users and ${polls.length}`); console.log("🌱 Seeded the database"); } catch (error) { From 9d8f6d41d0effbd0e5047fa8f13abeb68a5f57e5 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Mon, 14 Jul 2025 15:09:37 -0400 Subject: [PATCH 03/38] router.get by id --- api/poll.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/api/poll.js b/api/poll.js index 02868cb..ab95bc2 100644 --- a/api/poll.js +++ b/api/poll.js @@ -12,4 +12,18 @@ router.get("/", async (req, res) => { } }); -module.exports = router; +router.get("/:id", async (req, res) => { + try { + const poll = await Polls.findByPk(req.params.id); + if (!poll) { + return res.status(404).json({ error: "Poll not found" }); + } + res.json(poll); + } catch (error) { + console.error(error); + res.status(500).json({ error: "Failed to fetch poll" }); + } +}); + + +module.exports = router; \ No newline at end of file From bfd233fb2137b9382f7f049142a0a3093f3703e6 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Mon, 14 Jul 2025 15:28:17 -0400 Subject: [PATCH 04/38] router post created --- api/poll.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/api/poll.js b/api/poll.js index ab95bc2..183fa9d 100644 --- a/api/poll.js +++ b/api/poll.js @@ -25,5 +25,14 @@ router.get("/:id", async (req, res) => { } }); +router.post("/", async (req, res) => { + try { + const createPoll = await Polls.create(req.body); + res.status(201).send(createPoll); + } catch (error) { + console.error(error); + res.status(500).json({ error: "Failed to create poll" }); + } +}); module.exports = router; \ No newline at end of file From eef857951bee7fba7c92d0446b9f13541eab0644 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Tue, 15 Jul 2025 09:52:54 -0400 Subject: [PATCH 05/38] added a route for update handling of user profiles in index.js --- auth/index.js | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/auth/index.js b/auth/index.js index 07968c5..ea7a034 100644 --- a/auth/index.js +++ b/auth/index.js @@ -169,8 +169,8 @@ router.post("/login", async (req, res) => { // Find user const user = await User.findOne({ where: { username } }); - user.checkPassword(password); - if (!user) { + // Adjusted to make sure that we don't get null users + if (!user || !user.checkPassword(password)) { return res.status(401).send({ error: "Invalid credentials" }); } @@ -215,19 +215,35 @@ router.post("/logout", (req, res) => { }); // Get current user route (protected) -router.get("/me", (req, res) => { - const token = req.cookies.token; +router.put("/me", authenticateJWT, async (req, res) => { + try { + const { firstName, lastName, email, profilePicture } = req.body; + const user = await User.findByPk(req.user.id); - if (!token) { - return res.send({}); - } + if (!user) return res.status(404).send({ error: "User not found" }); - jwt.verify(token, JWT_SECRET, (err, user) => { - if (err) { - return res.status(403).send({ error: "Invalid or expired token" }); - } - res.send({ user: user }); - }); + if (firstName !== undefined) user.firstName = firstName; + if (lastName !== undefined) user.lastName = lastName; + if (email !== undefined) user.email = email; + if (profilePicture !== undefined) user.profilePicture = profilePicture; + + await user.save(); + + res.send({ + message: "Profile updated successfully", + user: { + id: user.id, + username: user.username, + email: user.email, + firstName: user.firstName, + lastName: user.lastName, + profilePicture: user.profilePicture, + }, + }); + } catch (err) { + console.error("Update profile error:", err); + res.status(500).send({ error: "Failed to update profile" }); + } }); module.exports = { router, authenticateJWT }; From 29e50ef328b1ae9728e79df6113a4604f5d2c9fe Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Tue, 15 Jul 2025 10:20:57 -0400 Subject: [PATCH 06/38] Update user.js with profile definitions (first/last name, profile pictures) --- database/user.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/database/user.js b/database/user.js index 755c757..ef7697a 100644 --- a/database/user.js +++ b/database/user.js @@ -28,6 +28,19 @@ const User = db.define("user", { type: DataTypes.STRING, allowNull: true, }, + firstName: { + type: DataTypes.STRING, + allowNull: true, + }, + lastName: { + type: DataTypes.STRING, + allowNull: true, + }, + profilePicture: { + type: DataTypes.STRING, + allowNull: true, + defaultValue: "https://i.imgur.com/default-avatar.png", + }, }); // Instance method to check password From 28080d2aade172be7901a1c582970001e671f93f Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 10:40:55 -0400 Subject: [PATCH 07/38] all routers for polls are finished --- api/poll.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/api/poll.js b/api/poll.js index 183fa9d..6d81443 100644 --- a/api/poll.js +++ b/api/poll.js @@ -25,6 +25,22 @@ router.get("/:id", async (req, res) => { } }); +router.patch("/:id", async (req, res) => { + try { + const poll = await Polls.findByPk(req.params.id); + if (!poll) { + return res.status(404).json({ error: "Poll not found" }); + } + + const updatedPoll = await poll.update(req.body); + res.send(updatedPoll); + } catch (error) { + console.error(error); + res.status(500).json({ error: "Failed to update poll" }); + } +}); + + router.post("/", async (req, res) => { try { const createPoll = await Polls.create(req.body); @@ -35,4 +51,18 @@ router.post("/", async (req, res) => { } }); +router.delete("/:id", async (req, res) => { + try { + const deletePoll = await Polls.findByPk(req.params.id); + if (!deletePoll) { + return res.status(404).json({ error: "Poll not found" }); + } + await deletePoll.destroy(); + res.sendStatus(200); + } catch (error) { + console.error(error); + res.status(500).json({ error: "Failed to delete poll" }); + } +}); + module.exports = router; \ No newline at end of file From dd9fcbb0ec04ffa9b9e7db8adcdca5133a796d63 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 11:22:02 -0400 Subject: [PATCH 08/38] made an admins table --- database/admins.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 database/admins.js diff --git a/database/admins.js b/database/admins.js new file mode 100644 index 0000000..dba2819 --- /dev/null +++ b/database/admins.js @@ -0,0 +1,24 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); +const bcrypt = require("bcrypt"); + +const Admin = + ("admins", + { + id: { + type: DataTypes.INTEGER, + autoIncrement: false, + primaryKey: true, + }, + email: { + type: DataTypes.STRING, + allownull: false, + }, + passwordHash: { + type: DataTypes.STRING, + allowNull: true, + }, + }, + { + timestamps: true, + }); From 8c17ef68c4cc8ca3ca418f1cc193502dd66e3d48 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 11:23:33 -0400 Subject: [PATCH 09/38] forgot de.define --- database/{admins.js => admin.js} | 3 +-- database/roles.js | 3 +++ 2 files changed, 4 insertions(+), 2 deletions(-) rename database/{admins.js => admin.js} (91%) create mode 100644 database/roles.js diff --git a/database/admins.js b/database/admin.js similarity index 91% rename from database/admins.js rename to database/admin.js index dba2819..7b807b9 100644 --- a/database/admins.js +++ b/database/admin.js @@ -2,8 +2,7 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); const bcrypt = require("bcrypt"); -const Admin = - ("admins", +const Admin = db.define ("admins", { id: { type: DataTypes.INTEGER, diff --git a/database/roles.js b/database/roles.js new file mode 100644 index 0000000..1fe2522 --- /dev/null +++ b/database/roles.js @@ -0,0 +1,3 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); +const bcrypt = require("bcrypt"); \ No newline at end of file From ca12671b7d2536d340d62689626f18f72c02b082 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 11:24:57 -0400 Subject: [PATCH 10/38] forgot module exports as well --- database/admin.js | 2 ++ database/roles.js | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/database/admin.js b/database/admin.js index 7b807b9..20dcdca 100644 --- a/database/admin.js +++ b/database/admin.js @@ -21,3 +21,5 @@ const Admin = db.define ("admins", { timestamps: true, }); + + module.exports = Admin; \ No newline at end of file diff --git a/database/roles.js b/database/roles.js index 1fe2522..935fb27 100644 --- a/database/roles.js +++ b/database/roles.js @@ -1,3 +1,4 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); -const bcrypt = require("bcrypt"); \ No newline at end of file +const bcrypt = require("bcrypt"); + From c4c1cc5d70d28982e18b249b9ba3f26cc8b81f4d Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 11:47:52 -0400 Subject: [PATCH 11/38] created a Roles table --- database/roles.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/database/roles.js b/database/roles.js index 935fb27..7ac89af 100644 --- a/database/roles.js +++ b/database/roles.js @@ -2,3 +2,24 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); const bcrypt = require("bcrypt"); +const Roles = db.define ("roles", + { + id: + { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true + }, + name: + { + type: DataTypes.STRING, + allowNull: false + }, + description: + { + type: DataTypes.TEXT, + allowNull: true + } + }); + + module.exports = Roles; \ No newline at end of file From 064fc106dcfd7ccbcfb307c6a5c37dffcc1ecb32 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 13:33:29 -0400 Subject: [PATCH 12/38] Created a Poll Invites table --- database/poll_Invites.js | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 database/poll_Invites.js diff --git a/database/poll_Invites.js b/database/poll_Invites.js new file mode 100644 index 0000000..dbf1396 --- /dev/null +++ b/database/poll_Invites.js @@ -0,0 +1,44 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); + +const PollInvite = db.define("poll_invite", { + id: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + poll_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { + model: "polls", + key: "id", + }, + }, + user_id: { + type: DataTypes.INTEGER, + allowNull: true, + references: { + model: "users", + key: "id", + }, + }, + email: { + type: DataTypes.STRING, + allowNull: false, + }, + status: { + type: DataTypes.STRING, + allowNull: false, + defaultValue: "pending", + validate: { + isIn: [["pending", "accepted", "declined"]], + }, + }, + sent_at: { + type: DataTypes.DATE, + defaultValue: DataTypes.NOW, + }, +}); + +module.exports = PollInvite; From 2435a4d1835cd000639347be0dd68b3ca92f86cc Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 14:02:08 -0400 Subject: [PATCH 13/38] created poll_options table --- database/poll_options.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 database/poll_options.js diff --git a/database/poll_options.js b/database/poll_options.js new file mode 100644 index 0000000..957aaa8 --- /dev/null +++ b/database/poll_options.js @@ -0,0 +1,24 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); + +const PollOptions = db.define("poll options", { + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + text: { + type: DataTypes.STRING, + allowNull: false, + }, + pollId: { + type: DataTypes.INTEGER, + allowNull: false, + references: { + model: "polls", + key: "id", + }, + }, +}); + +module.exports = PollOption; From d3b45496e6e7f3523dcf501c6802e2d351baaa3f Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 14:55:41 -0400 Subject: [PATCH 14/38] set up associations and corrected poll options --- database/Polls.js | 2 +- database/index.js | 8 ++++++++ database/poll_options.js | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/database/Polls.js b/database/Polls.js index 63737d2..e02992c 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -16,7 +16,7 @@ const Polls = db.define("polls", { }, }, title: { - type: DataTypes.STRING, + type: DataTypes.STRING, allowNull: false, }, description: { diff --git a/database/index.js b/database/index.js index 22744a9..e9d366d 100644 --- a/database/index.js +++ b/database/index.js @@ -1,10 +1,18 @@ const db = require("./db"); const User = require("./user"); const Polls = require("./Polls"); +const PollOption = require("./poll_options"); + +Polls.belongsTo(User); +User.hasMany(Polls), + +Polls.hasMany(PollOption); +PollOption.belongsTo(Polls); module.exports = { db, User, Polls, + PollOption, }; diff --git a/database/poll_options.js b/database/poll_options.js index 957aaa8..e82f6fc 100644 --- a/database/poll_options.js +++ b/database/poll_options.js @@ -1,7 +1,7 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); -const PollOptions = db.define("poll options", { +const PollOptions = db.define("poll_option", { id: { type: DataTypes.INTEGER, autoIncrement: true, @@ -21,4 +21,4 @@ const PollOptions = db.define("poll options", { }, }); -module.exports = PollOption; +module.exports = PollOptions; From e5426bd6b5f4336947d33125bcd301ad012dda0e Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 14:58:22 -0400 Subject: [PATCH 15/38] changed description in polls table so the null is false instead of true --- database/Polls.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/Polls.js b/database/Polls.js index e02992c..9d7652e 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -21,7 +21,7 @@ const Polls = db.define("polls", { }, description: { type: DataTypes.TEXT, - allowNull: true, + allowNull: false, }, isActive: { type: DataTypes.BOOLEAN, From 6559020f647b08d8e8312f4621f633d765fc7c06 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Tue, 15 Jul 2025 15:47:28 -0400 Subject: [PATCH 16/38] created ballots table --- database/Polls.js | 9 +++------ database/ballot.js | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 database/ballot.js diff --git a/database/Polls.js b/database/Polls.js index 9d7652e..15ce058 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -8,12 +8,9 @@ const Polls = db.define("polls", { primaryKey: true, }, user_id: { - type: DataTypes.INTEGER, - allowNull: false, - references: { - model: "users", - key: "id", - }, + type: DataTypes.INTEGER, + allowNull: false, + references: { model: 'users', key: 'id' } }, title: { type: DataTypes.STRING, diff --git a/database/ballot.js b/database/ballot.js new file mode 100644 index 0000000..aec8833 --- /dev/null +++ b/database/ballot.js @@ -0,0 +1,24 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); + +const Ballot = db.define("ballot", { + id: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + poll_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { model: "polls", key: "id" }, + }, + user_id: { + type: DataTypes.INTEGER, + allowNull: true, + references: { model: "users", key: "id" }, + }, + submitted_at: { + type: DataTypes.DATE, + defaultValue: "", // I'm not sure what to put for this yet + }, +}); From 31caf2984fd58367aaea4bce6a57dfaec1b2efe3 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:19:51 -0400 Subject: [PATCH 17/38] Updated app.js with poll import and routing --- app.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app.js b/app.js index 5857036..3600323 100644 --- a/app.js +++ b/app.js @@ -13,6 +13,8 @@ const cors = require("cors"); const PORT = process.env.PORT || 8080; const FRONTEND_URL = process.env.FRONTEND_URL || "http://localhost:3000"; +const pollRoutes = require("./routes/poll"); + // body parser middleware app.use(express.json()); @@ -30,6 +32,7 @@ app.use(morgan("dev")); // logging middleware app.use(express.static(path.join(__dirname, "public"))); // serve static files from public folder app.use("/api", apiRouter); // mount api router app.use("/auth", authRouter); // mount auth router +app.use("/polls", pollRoutes); // Added poll routes // error handling middleware app.use((err, req, res, next) => { From b288ebc5d62ba97fdd04b84390c95c7ae1fdb96e Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:27:33 -0400 Subject: [PATCH 18/38] Updated poll.js and improved poll id logic --- api/poll.js | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/api/poll.js b/api/poll.js index 6d81443..f42f6c1 100644 --- a/api/poll.js +++ b/api/poll.js @@ -1,6 +1,7 @@ const express = require("express"); const router = express.Router(); const { Polls } = require("../database"); +const { Polls, Option } = require("../database"); router.get("/", async (req, res) => { try { @@ -12,16 +13,28 @@ router.get("/", async (req, res) => { } }); +// Adjusted poll id logic to include options, more info and vote count router.get("/:id", async (req, res) => { try { - const poll = await Polls.findByPk(req.params.id); - if (!poll) { - return res.status(404).json({ error: "Poll not found" }); - } - res.json(poll); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Failed to fetch poll" }); + const poll = await Polls.findByPk(req.params.id, { + include: [Option], + }); + + if (!poll) return res.status(404).send({ error: "Poll not found" }); + + const totalVotes = poll.options.reduce((sum, opt) => sum + opt.votes, 0); + res.send({ + id: poll.id, + title: poll.title, + description: poll.description, + status: poll.status, + endTime: poll.endTime, + options: poll.options, + totalVotes, + }); + } catch (err) { + console.error("Error getting poll:", err); + res.status(500).send({ error: "Server error" }); } }); @@ -65,4 +78,4 @@ router.delete("/:id", async (req, res) => { } }); -module.exports = router; \ No newline at end of file +module.exports = router; From 80d3d5c41105a7316dc3f0b0158517b4c4479897 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:33:37 -0400 Subject: [PATCH 19/38] Updated poll.js to remove duplicate line --- api/poll.js | 1 - 1 file changed, 1 deletion(-) diff --git a/api/poll.js b/api/poll.js index f42f6c1..21fe3ab 100644 --- a/api/poll.js +++ b/api/poll.js @@ -1,6 +1,5 @@ const express = require("express"); const router = express.Router(); -const { Polls } = require("../database"); const { Polls, Option } = require("../database"); router.get("/", async (req, res) => { From a6aa1f66c473d916b53f39a1cb2b68ec4f17899d Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:37:50 -0400 Subject: [PATCH 20/38] Updated Polls.js to handle option support --- database/Polls.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/database/Polls.js b/database/Polls.js index 15ce058..2090f46 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -28,4 +28,12 @@ const Polls = db.define("polls", { timestamps: true, }); +Polls.associate = (models) => { + Polls.hasMany(models.Option, { + foreignKey: "pollId", + as: "options", + onDelete: "CASCADE", + }); +}; + module.exports = Polls; From e0b3b5fc740881be983dcedf5f7f7d0166e46f7b Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:42:38 -0400 Subject: [PATCH 21/38] Updated Polls.js to reflect options naming --- database/Polls.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/Polls.js b/database/Polls.js index 2090f46..181d064 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -29,7 +29,7 @@ const Polls = db.define("polls", { }); Polls.associate = (models) => { - Polls.hasMany(models.Option, { + Polls.hasMany(models.PollOptions, { foreignKey: "pollId", as: "options", onDelete: "CASCADE", From 42a871e34c71517ed475d26c1437faf6ad231f27 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:43:55 -0400 Subject: [PATCH 22/38] Update poll_options.js --- database/poll_options.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/database/poll_options.js b/database/poll_options.js index e82f6fc..a2b446e 100644 --- a/database/poll_options.js +++ b/database/poll_options.js @@ -21,4 +21,11 @@ const PollOptions = db.define("poll_option", { }, }); +PollOptions.associate = (models) => { + PollOptions.belongsTo(models.Polls, { + foreignKey: "pollId", + as: "poll", + }); +}; + module.exports = PollOptions; From 23793b3df928123e377ca9266ce7f4e5b2ea6719 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:50:33 -0400 Subject: [PATCH 23/38] Updated index.js with poll associations --- database/index.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/database/index.js b/database/index.js index e9d366d..e0fa353 100644 --- a/database/index.js +++ b/database/index.js @@ -3,11 +3,21 @@ const User = require("./user"); const Polls = require("./Polls"); const PollOption = require("./poll_options"); -Polls.belongsTo(User); -User.hasMany(Polls), +Polls.belongsTo(User, { foreignKey: "user_id" }); +User.hasMany(Polls, { foreignKey: "user_id" }); -Polls.hasMany(PollOption); -PollOption.belongsTo(Polls); +Polls.hasMany(PollOption, { + foreignKey: "pollId", + as: "options", + onDelete: "CASCADE", +}); +PollOption.belongsTo(Polls, { + foreignKey: "pollId", + as: "poll", +}); + +Polls.associate?.({ PollOption }); +PollOption.associate?.({ Polls }); module.exports = { db, From 18d9fa513217cef8636da2a69d856062b85bae7d Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:52:34 -0400 Subject: [PATCH 24/38] Updated poll.js with option handling adjustments --- api/poll.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/api/poll.js b/api/poll.js index 21fe3ab..0e77f50 100644 --- a/api/poll.js +++ b/api/poll.js @@ -16,12 +16,13 @@ router.get("/", async (req, res) => { router.get("/:id", async (req, res) => { try { const poll = await Polls.findByPk(req.params.id, { - include: [Option], + include: [{ model: PollOption, as: "options" }], }); if (!poll) return res.status(404).send({ error: "Poll not found" }); - const totalVotes = poll.options.reduce((sum, opt) => sum + opt.votes, 0); + const totalVotes = poll.options.reduce((sum, opt) => sum + (opt.votes || 0), 0); + res.send({ id: poll.id, title: poll.title, @@ -37,6 +38,7 @@ router.get("/:id", async (req, res) => { } }); + router.patch("/:id", async (req, res) => { try { const poll = await Polls.findByPk(req.params.id); From 51b923210c6614b59c4861d1380ba8eed093906c Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 08:53:18 -0400 Subject: [PATCH 25/38] Update poll.js --- api/poll.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/poll.js b/api/poll.js index 0e77f50..1918a0f 100644 --- a/api/poll.js +++ b/api/poll.js @@ -1,6 +1,6 @@ const express = require("express"); const router = express.Router(); -const { Polls, Option } = require("../database"); +const { Polls, PollOptions } = require("../database"); router.get("/", async (req, res) => { try { From 39e99ffb3515e481a41dbf3034f2ab76da13b4fa Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 09:04:32 -0400 Subject: [PATCH 26/38] Update poll.js typo in import --- api/poll.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/poll.js b/api/poll.js index 1918a0f..be6195b 100644 --- a/api/poll.js +++ b/api/poll.js @@ -1,6 +1,6 @@ const express = require("express"); const router = express.Router(); -const { Polls, PollOptions } = require("../database"); +const { Polls, PollOption } = require("../database"); router.get("/", async (req, res) => { try { From ab3c4732d1f4cdae6b855fe2467071044b60cc4c Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 11:37:29 -0400 Subject: [PATCH 27/38] Updated poll.js with publishing protections --- api/poll.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/api/poll.js b/api/poll.js index be6195b..fd493ee 100644 --- a/api/poll.js +++ b/api/poll.js @@ -42,10 +42,16 @@ router.get("/:id", async (req, res) => { router.patch("/:id", async (req, res) => { try { const poll = await Polls.findByPk(req.params.id); + if (!poll) { return res.status(404).json({ error: "Poll not found" }); } + // Stop users from editing a poll after it's been published or ended + if (["published", "ended"].includes(poll.status)) { + return res.status(400).json({ error: "Cannot edit a published or ended poll" }); + } + const updatedPoll = await poll.update(req.body); res.send(updatedPoll); } catch (error) { @@ -65,12 +71,49 @@ router.post("/", async (req, res) => { } }); +// Publishing logic and validation added +router.put("/publish/:id", async (req, res) => { + try { + const poll = await Polls.findByPk(req.params.id, { + include: [{ model: PollOption, as: "options" }], + }); + + if (!poll) return res.status(404).json({ error: "Poll not found" }); + if (poll.status !== "draft") return res.status(400).json({ error: "Only draft polls can be published" }); + + if (!poll.title || !poll.description) { + return res.status(400).json({ error: "Title and description are required to publish" }); + } + + if (!poll.options || poll.options.length < 2) { + return res.status(400).json({ error: "Poll must have at least two options to publish" }); + } + + poll.status = "published"; + poll.publishedAt = new Date(); + await poll.save(); + + res.send({ message: "Poll published successfully", poll }); + } catch (err) { + console.error("Publish error:", err); + res.status(500).json({ error: "Failed to publish poll" }); + } +}); + + router.delete("/:id", async (req, res) => { try { const deletePoll = await Polls.findByPk(req.params.id); + if (!deletePoll) { return res.status(404).json({ error: "Poll not found" }); } + + // Protects against polls getting deleted once published + if (["published", "ended"].includes(deletePoll.status)) { + return res.status(400).json({ error: "Cannot delete a published or ended poll" }); + } + await deletePoll.destroy(); res.sendStatus(200); } catch (error) { From db6f5b7453ed67bfcd9d505bb79215ca4ad5d0da Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:21:38 -0400 Subject: [PATCH 28/38] temporaily commented out associations and making ballots,votes table --- app.js | 4 ++-- database/Polls.js | 15 ++++++++------- database/ballot.js | 3 ++- database/index.js | 30 +++++++++++++++++------------- database/vote.js | 26 ++++++++++++++++++++++++++ 5 files changed, 55 insertions(+), 23 deletions(-) create mode 100644 database/vote.js diff --git a/app.js b/app.js index 3600323..511796d 100644 --- a/app.js +++ b/app.js @@ -13,7 +13,7 @@ const cors = require("cors"); const PORT = process.env.PORT || 8080; const FRONTEND_URL = process.env.FRONTEND_URL || "http://localhost:3000"; -const pollRoutes = require("./routes/poll"); +// const pollRoutes = require("./routes/poll"); // body parser middleware app.use(express.json()); @@ -32,7 +32,7 @@ app.use(morgan("dev")); // logging middleware app.use(express.static(path.join(__dirname, "public"))); // serve static files from public folder app.use("/api", apiRouter); // mount api router app.use("/auth", authRouter); // mount auth router -app.use("/polls", pollRoutes); // Added poll routes +// app.use("/polls", pollRoutes); // Added poll routes // error handling middleware app.use((err, req, res, next) => { diff --git a/database/Polls.js b/database/Polls.js index 181d064..de58791 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -1,6 +1,7 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); + const Polls = db.define("polls", { id: { type: DataTypes.INTEGER, @@ -28,12 +29,12 @@ const Polls = db.define("polls", { timestamps: true, }); -Polls.associate = (models) => { - Polls.hasMany(models.PollOptions, { - foreignKey: "pollId", - as: "options", - onDelete: "CASCADE", - }); -}; +// Polls.associate = (models) => { +// Polls.hasMany(models.PollOptions, { +// foreignKey: "pollId", +// as: "options", +// onDelete: "CASCADE", +// }); +// }; module.exports = Polls; diff --git a/database/ballot.js b/database/ballot.js index aec8833..ee5556c 100644 --- a/database/ballot.js +++ b/database/ballot.js @@ -19,6 +19,7 @@ const Ballot = db.define("ballot", { }, submitted_at: { type: DataTypes.DATE, - defaultValue: "", // I'm not sure what to put for this yet + defaultValue: DataTypes.NOW, // I'm not sure what to put for this yet }, }); + diff --git a/database/index.js b/database/index.js index e0fa353..749f64d 100644 --- a/database/index.js +++ b/database/index.js @@ -3,21 +3,25 @@ const User = require("./user"); const Polls = require("./Polls"); const PollOption = require("./poll_options"); -Polls.belongsTo(User, { foreignKey: "user_id" }); -User.hasMany(Polls, { foreignKey: "user_id" }); +Polls.belongsTo(User); +User.hasMany(Polls); -Polls.hasMany(PollOption, { - foreignKey: "pollId", - as: "options", - onDelete: "CASCADE", -}); -PollOption.belongsTo(Polls, { - foreignKey: "pollId", - as: "poll", -}); +Polls.hasMany(PollOption); +PollOption.belongsTo(Polls); -Polls.associate?.({ PollOption }); -PollOption.associate?.({ Polls }); +// Polls.hasMany(PollOption, { +// foreignKey: "pollId", +// as: "options", +// onDelete: "CASCADE", +// }); + +// PollOption.belongsTo(Polls, { +// foreignKey: "pollId", +// as: "poll", +// }); + +// Polls.associate?.({ PollOption }); +// PollOption.associate?.({ Polls }); module.exports = { db, diff --git a/database/vote.js b/database/vote.js new file mode 100644 index 0000000..b9d59c4 --- /dev/null +++ b/database/vote.js @@ -0,0 +1,26 @@ +const { DataTypes } = require("sequelize"); +const db = require("./db"); + +const Vote = db.define("vote", { + id: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + ballot_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { model: "ballots", key: "id" }, + }, + poll_option_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { model: "poll_options", key: "id" }, + }, + rank: { + type: DataTypes.INTEGER, + allowNull: true, + }, +}); + +module.exports = Vote; From 625e11114f9fb4c97e95798df6b382631f7ab013 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:28:33 -0400 Subject: [PATCH 29/38] ballot and vote association --- database/index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/database/index.js b/database/index.js index 749f64d..da88cb5 100644 --- a/database/index.js +++ b/database/index.js @@ -9,6 +9,9 @@ User.hasMany(Polls); Polls.hasMany(PollOption); PollOption.belongsTo(Polls); +Ballot.hasMany(Vote); +Vote.belongsTo(Ballot); + // Polls.hasMany(PollOption, { // foreignKey: "pollId", // as: "options", From 56199815252a31d92dcdbe3bc873576e43ad6293 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:31:17 -0400 Subject: [PATCH 30/38] forgot to do exports and needed to require ballot and vote at line 5 and 6 --- database/index.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/database/index.js b/database/index.js index da88cb5..70eaa37 100644 --- a/database/index.js +++ b/database/index.js @@ -2,10 +2,13 @@ const db = require("./db"); const User = require("./user"); const Polls = require("./Polls"); const PollOption = require("./poll_options"); +const Vote = require("./vote") +const Ballot = require("ballot") Polls.belongsTo(User); User.hasMany(Polls); + Polls.hasMany(PollOption); PollOption.belongsTo(Polls); @@ -31,5 +34,7 @@ module.exports = { User, Polls, PollOption, + Ballot, + Vote, }; From 626f24f85de67dac21574a98074e9056d4c6eaa2 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:33:54 -0400 Subject: [PATCH 31/38] forgot to put module.exports = Ballot --- database/ballot.js | 1 + database/index.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/database/ballot.js b/database/ballot.js index ee5556c..f1b75c5 100644 --- a/database/ballot.js +++ b/database/ballot.js @@ -23,3 +23,4 @@ const Ballot = db.define("ballot", { }, }); +module.exports = Ballot; diff --git a/database/index.js b/database/index.js index 70eaa37..fb12cfa 100644 --- a/database/index.js +++ b/database/index.js @@ -3,7 +3,7 @@ const User = require("./user"); const Polls = require("./Polls"); const PollOption = require("./poll_options"); const Vote = require("./vote") -const Ballot = require("ballot") +const Ballot = require("./ballot") Polls.belongsTo(User); User.hasMany(Polls); From d0f0f58a6b45733e2ecd0ada88ade54d36c39109 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:46:09 -0400 Subject: [PATCH 32/38] did more associations --- database/index.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/database/index.js b/database/index.js index fb12cfa..d03dfa4 100644 --- a/database/index.js +++ b/database/index.js @@ -8,10 +8,15 @@ const Ballot = require("./ballot") Polls.belongsTo(User); User.hasMany(Polls); - Polls.hasMany(PollOption); PollOption.belongsTo(Polls); +Ballot.belongsTo(Polls); +Ballot.belongsTo(User); + +Vote.belongsTo(PollOption); +PollOption.hasMany(Vote); + Ballot.hasMany(Vote); Vote.belongsTo(Ballot); From dea00645bbbb73a12d9058927990675d0b267d56 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 14:52:00 -0400 Subject: [PATCH 33/38] correction --- database/index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/database/index.js b/database/index.js index d03dfa4..ade7e29 100644 --- a/database/index.js +++ b/database/index.js @@ -14,12 +14,15 @@ PollOption.belongsTo(Polls); Ballot.belongsTo(Polls); Ballot.belongsTo(User); +Polls.hasMany(Ballot); + Vote.belongsTo(PollOption); PollOption.hasMany(Vote); Ballot.hasMany(Vote); Vote.belongsTo(Ballot); + // Polls.hasMany(PollOption, { // foreignKey: "pollId", // as: "options", From cd04ca44d4a757c16c7f393f9f32c9e1a2078d70 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Wed, 16 Jul 2025 15:51:49 -0400 Subject: [PATCH 34/38] ballot router but not tested in postman, does not break the abckend though --- api/ballot.js | 35 +++++++++++++++++++++++++++++++++++ api/index.js | 5 ++++- database/index.js | 1 - 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 api/ballot.js diff --git a/api/ballot.js b/api/ballot.js new file mode 100644 index 0000000..04d3c42 --- /dev/null +++ b/api/ballot.js @@ -0,0 +1,35 @@ +const express = require("express"); +const router = express.Router(); +const { Ballot, Vote, Polls, PollOption, User } = require("../database"); + +router.post("/", async (req, res) => { + try { + const { pollId, userId, votes } = req.body; + + if (!pollId || !votes || votes.length < 2) { + return res.status(400).json({ error: "Poll ID and at least 2 ranked votes are required." }); + } + + const poll = await Polls.findByPk(pollId); + if (!poll) { + return res.status(404).json({ error: "Poll not found." }); + } + + if (userId) { + const user = await User.findByPk(userId); + if (!user) { + return res.status(404).json({ error: "User not found." }); + } + + const existingBallot = await Ballot.findOne({ where: { poll_id: pollId, user_id: userId } }); + if (existingBallot) { + return res.status(400).json({ error: "User has already submitted a ballot for this poll." }); + } + } + } catch (err) { + console.error(err); + res.status(500).json({ error: "Failed to submit ballot." }); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/api/index.js b/api/index.js index eb55059..87ee3c3 100644 --- a/api/index.js +++ b/api/index.js @@ -1,10 +1,13 @@ const express = require("express"); const router = express.Router(); + const testDbRouter = require("./test-db"); +const ballotsRouter = require("./ballot"); // const usersRouter = require("./user"); const pollsRouter = require("./poll"); -router.use("/Polls", pollsRouter); +router.use("/Polls", pollsRouter); +router.use("/ballots", ballotsRouter); router.use("/test-db", testDbRouter); module.exports = router; diff --git a/database/index.js b/database/index.js index ade7e29..61db1bf 100644 --- a/database/index.js +++ b/database/index.js @@ -22,7 +22,6 @@ PollOption.hasMany(Vote); Ballot.hasMany(Vote); Vote.belongsTo(Ballot); - // Polls.hasMany(PollOption, { // foreignKey: "pollId", // as: "options", From f68d3696d23e0961ebb4f75f58d63ed73fb94af5 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 21:49:49 -0400 Subject: [PATCH 35/38] fixed associations bug; api call test was successful --- database/index.js | 55 ++++++++++++++++++++-------------------- database/poll_options.js | 7 ----- database/seed.js | 23 ++++++++++++----- 3 files changed, 44 insertions(+), 41 deletions(-) diff --git a/database/index.js b/database/index.js index fb12cfa..c9ece0b 100644 --- a/database/index.js +++ b/database/index.js @@ -2,32 +2,34 @@ const db = require("./db"); const User = require("./user"); const Polls = require("./Polls"); const PollOption = require("./poll_options"); -const Vote = require("./vote") -const Ballot = require("./ballot") - -Polls.belongsTo(User); -User.hasMany(Polls); - - -Polls.hasMany(PollOption); -PollOption.belongsTo(Polls); - -Ballot.hasMany(Vote); -Vote.belongsTo(Ballot); - -// Polls.hasMany(PollOption, { -// foreignKey: "pollId", -// as: "options", -// onDelete: "CASCADE", -// }); - -// PollOption.belongsTo(Polls, { -// foreignKey: "pollId", -// as: "poll", -// }); - -// Polls.associate?.({ PollOption }); -// PollOption.associate?.({ Polls }); +const Vote = require("./vote"); +const Ballot = require("./ballot"); + +//Bidirectional relationship logic +// USER ↔ POLLS +Polls.belongsTo(User, { foreignKey: "user_id" }); +User.hasMany(Polls, { foreignKey: "user_id" }); + +// POLLS ↔ OPTIONS +Polls.hasMany(PollOption, { + foreignKey: "pollId", + as: "options", + onDelete: "CASCADE", +}); +PollOption.belongsTo(Polls, { + foreignKey: "pollId", + as: "poll", +}); + +// BALLOT ↔ VOTE +Ballot.hasMany(Vote, { + foreignKey: "ballotId", + as: "votes", +}); +Vote.belongsTo(Ballot, { + foreignKey: "ballotId", + as: "ballot", +}); module.exports = { db, @@ -37,4 +39,3 @@ module.exports = { Ballot, Vote, }; - diff --git a/database/poll_options.js b/database/poll_options.js index a2b446e..e82f6fc 100644 --- a/database/poll_options.js +++ b/database/poll_options.js @@ -21,11 +21,4 @@ const PollOptions = db.define("poll_option", { }, }); -PollOptions.associate = (models) => { - PollOptions.belongsTo(models.Polls, { - foreignKey: "pollId", - as: "poll", - }); -}; - module.exports = PollOptions; diff --git a/database/seed.js b/database/seed.js index 5622e00..b48fd96 100644 --- a/database/seed.js +++ b/database/seed.js @@ -1,49 +1,58 @@ const db = require("./db"); -const { User } = require("./index"); -const { Polls } = require("./index.js") +const { User, Polls, PollOption } = require("./index"); const seed = async () => { try { db.logging = false; await db.sync({ force: true }); // Drop and recreate tables + // Create users const users = await User.bulkCreate([ { username: "admin", passwordHash: User.hashPassword("admin123") }, { username: "user1", passwordHash: User.hashPassword("user111") }, { username: "user2", passwordHash: User.hashPassword("user222") }, ]); + // Create polls const polls = await Polls.bulkCreate([ { user_id: users[0].id, title: "What is your favorite programming language?", description: "Vote for the language you love the most!", + status: "published", // test view logic isActive: true, }, { user_id: users[1].id, - title: "Do you prefer remote or inperson work?", + title: "Do you prefer remote or in-person work?", description: "Let us settle this once and for all.", isActive: true, }, { user_id: users[2].id, - title: "Whats your favorite resturant?", + title: "What's your favorite restaurant?", description: "Vote yes or no for an offsite trip.", isActive: false, }, ]); - - console.log(`šŸ‘¤ Created ${users.length} users and ${polls.length}`); + // Options for the first poll + await PollOption.bulkCreate([ + { text: "JavaScript", pollId: polls[0].id, votes: 3 }, + { text: "Python", pollId: polls[0].id, votes: 2 }, + { text: "C++", pollId: polls[0].id, votes: 1 }, + ]); + + console.log(`šŸ‘¤ Created ${users.length} users and ${polls.length} polls`); console.log("🌱 Seeded the database"); } catch (error) { console.error("Error seeding database:", error); if (error.message.includes("does not exist")) { console.log("\nšŸ¤”šŸ¤”šŸ¤” Have you created your database??? šŸ¤”šŸ¤”šŸ¤”"); } + } finally { + db.close(); } - db.close(); }; seed(); From eee771d4c35c11f455c70e8556814ac7b757f364 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Wed, 16 Jul 2025 23:28:17 -0400 Subject: [PATCH 36/38] added duplication routes --- api/poll.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/api/poll.js b/api/poll.js index fd493ee..60a6350 100644 --- a/api/poll.js +++ b/api/poll.js @@ -71,6 +71,43 @@ router.post("/", async (req, res) => { } }); +// Duplication logic +router.post("/:id/duplicate", async (req, res) => { + try { + const originalPoll = await Polls.findByPk(req.params.id, { + include: [{ model: PollOption, as: "options" }], + }); + + if (!originalPoll) return res.status(404).json({ error: "Poll not found" }); + + const duplicatedPoll = await Polls.create({ + user_id: originalPoll.user_id, // or req.user.id if we're using auth + title: originalPoll.title + " (Copy)", + description: originalPoll.description, + status: "draft", + }); + + const duplicatedOptions = await Promise.all( + originalPoll.options.map((opt) => + PollOption.create({ + text: opt.text, + votes: 0, + pollId: duplicatedPoll.id, + }) + ) + ); + + res.status(201).json({ + message: "Poll duplicated successfully", + poll: duplicatedPoll, + options: duplicatedOptions, + }); + } catch (err) { + console.error("Duplicate poll error:", err); + res.status(500).json({ error: "Failed to duplicate poll" }); + } +}); + // Publishing logic and validation added router.put("/publish/:id", async (req, res) => { try { From 1781f21d41e874c2113a8a77fa319a62acb95236 Mon Sep 17 00:00:00 2001 From: TJordan77 Date: Thu, 17 Jul 2025 00:51:55 -0400 Subject: [PATCH 37/38] added routes for manually closing polls --- api/poll.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/api/poll.js b/api/poll.js index 60a6350..e5d5e26 100644 --- a/api/poll.js +++ b/api/poll.js @@ -21,6 +21,13 @@ router.get("/:id", async (req, res) => { if (!poll) return res.status(404).send({ error: "Poll not found" }); + // Checking if the poll should transition to "ended" + const now = new Date(); + if (poll.status === "published" && poll.endTime && new Date(poll.endTime) <= now) { + poll.status = "ended"; + await poll.save(); + } + const totalVotes = poll.options.reduce((sum, opt) => sum + (opt.votes || 0), 0); res.send({ @@ -28,6 +35,7 @@ router.get("/:id", async (req, res) => { title: poll.title, description: poll.description, status: poll.status, + publishedAt: poll.publishedAt, // including this for clarity endTime: poll.endTime, options: poll.options, totalVotes, @@ -52,6 +60,15 @@ router.patch("/:id", async (req, res) => { return res.status(400).json({ error: "Cannot edit a published or ended poll" }); } + // Included validation fields + const { title, description } = req.body; + if (title !== undefined && !title.trim()) { + return res.status(400).json({ error: "Title cannot be empty" }); + } + if (description !== undefined && !description.trim()) { + return res.status(400).json({ error: "Description cannot be empty" }); + } + const updatedPoll = await poll.update(req.body); res.send(updatedPoll); } catch (error) { @@ -61,6 +78,7 @@ router.patch("/:id", async (req, res) => { }); + router.post("/", async (req, res) => { try { const createPoll = await Polls.create(req.body); @@ -137,6 +155,26 @@ router.put("/publish/:id", async (req, res) => { } }); +// Manually close the polls +router.put("/:id/end", async (req, res) => { + try { + const poll = await Polls.findByPk(req.params.id); + + if (!poll) return res.status(404).json({ error: "Poll not found" }); + if (poll.status !== "published") { + return res.status(400).json({ error: "Only published polls can be ended" }); + } + + poll.status = "ended"; + await poll.save(); + + res.json({ message: "Poll ended successfully", poll }); + } catch (error) { + console.error("Error ending poll:", error); + res.status(500).json({ error: "Failed to end poll" }); + } +}); + router.delete("/:id", async (req, res) => { try { From f63f2bafba1410ab64dfc81c90e446e5c2dc4a40 Mon Sep 17 00:00:00 2001 From: Dagostocsc Date: Fri, 18 Jul 2025 14:40:06 -0400 Subject: [PATCH 38/38] suceeded in postman option route, troubleshooting user routes still --- api/index.js | 1 + api/poll.js | 42 ++++++++++++++++++++++++++++ database/Polls.js | 71 ++++++++++++++++++++++++----------------------- database/index.js | 19 +++++++++++++ 4 files changed, 99 insertions(+), 34 deletions(-) diff --git a/api/index.js b/api/index.js index 87f5ad1..05b1282 100644 --- a/api/index.js +++ b/api/index.js @@ -8,6 +8,7 @@ const pollsRouter = require("./poll"); router.use("/Polls", pollsRouter); router.use("/ballots", ballotsRouter); +router.use("/users", usersRouter); router.use("/test-db", testDbRouter); module.exports = router; diff --git a/api/poll.js b/api/poll.js index e5d5e26..fef9534 100644 --- a/api/poll.js +++ b/api/poll.js @@ -28,6 +28,10 @@ router.get("/:id", async (req, res) => { await poll.save(); } + //issue in creating the options from the polls themselves, do it as a separate functions in the router.post + // for options and not just for polls + + const totalVotes = poll.options.reduce((sum, opt) => sum + (opt.votes || 0), 0); res.send({ @@ -126,6 +130,44 @@ router.post("/:id/duplicate", async (req, res) => { } }); +router.post("/:id/options", async (req, res) => { + try { + const { id: pollId } = req.params; + const { text } = req.body; + + // Validate text + if (!text || !text.trim()) { + return res.status(400).json({ error: "Option text is required." }); + } + + // Check that poll exists + const poll = await Polls.findByPk(pollId); + if (!poll) { + return res.status(404).json({ error: "Poll not found." }); + } + + // Check that poll is in draft state + if (poll.status !== "draft") { + return res.status(400).json({ error: "Cannot add options to a published or ended poll." }); + } + + // Create the option + const newOption = await PollOption.create({ + text, + pollId: poll.id, + }); + + res.status(201).json({ + message: "Option added successfully.", + option: newOption, + }); + } catch (err) { + console.error("Error adding poll option:", err); + res.status(500).json({ error: "Failed to add option." }); + } +}); + + // Publishing logic and validation added router.put("/publish/:id", async (req, res) => { try { diff --git a/database/Polls.js b/database/Polls.js index de58791..1f30b5d 100644 --- a/database/Polls.js +++ b/database/Polls.js @@ -1,40 +1,43 @@ const { DataTypes } = require("sequelize"); const db = require("./db"); - -const Polls = db.define("polls", { - id: { - type: DataTypes.INTEGER, - autoIncrement: true, - primaryKey: true, - }, - user_id: { - type: DataTypes.INTEGER, - allowNull: false, - references: { model: 'users', key: 'id' } - }, - title: { - type: DataTypes.STRING, - allowNull: false, +const Polls = db.define( + "polls", + { + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + user_id: { + type: DataTypes.INTEGER, + allowNull: false, + references: { model: "users", key: "id" }, + }, + title: { + type: DataTypes.STRING, + allowNull: false, + }, + description: { + type: DataTypes.TEXT, + allowNull: false, + }, + isActive: { + type: DataTypes.BOOLEAN, + defaultValue: true, + }, + status: { + type: DataTypes.STRING, + allowNull: false, + defaultValue: "draft", + validate: { + isIn: [["draft", "published", "ended"]], + }, + }, }, - description: { - type: DataTypes.TEXT, - allowNull: false, - }, - isActive: { - type: DataTypes.BOOLEAN, - defaultValue: true, - }, -}, { - timestamps: true, -}); - -// Polls.associate = (models) => { -// Polls.hasMany(models.PollOptions, { -// foreignKey: "pollId", -// as: "options", -// onDelete: "CASCADE", -// }); -// }; + { + timestamps: true, + } +); module.exports = Polls; diff --git a/database/index.js b/database/index.js index c9ece0b..82154c5 100644 --- a/database/index.js +++ b/database/index.js @@ -31,6 +31,25 @@ Vote.belongsTo(Ballot, { as: "ballot", }); +Ballot.belongsTo(Polls, { + foreignKey: "poll_id", + as: "poll", +}); + +Ballot.belongsTo(User, { + foreignKey: "user_id", + as: "user", +}); + +Vote.belongsTo(PollOption, { + foreignKey: "pollOptionId", + as: "option", +}); +PollOption.hasMany(Vote, { + foreignKey: "pollOptionId", + as: "votes", +}); + module.exports = { db, User,