Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Back end #29

Merged
merged 3 commits into from
Dec 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 117 additions & 47 deletions server/controllers/alert.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,78 +2,148 @@ import db from '../database/db.js'

const alertController = {
getAlert: async (req, res) => {
const { id } = req.params

const alert = await db.query(
`SELECT * FROM "Notification" WHERE "NotificationId" = $1;`,
[id]
)
try {
const { id } = req.params

// get alert
const result = await db.query(
`SELECT N.*
FROM "Notification" AS N, "RecieveNotification" AS R
WHERE N."notificationId" = R."notificationId" AND
R."captainId" = $1 AND
N."notificationId" = $2;`,
[req.captain.captainId, id]
)

if (!alert.rowCount)
return res.status(404).json({ error: 'Alert not found' })
if (!result.rowCount)
return res.status(404).json({ error: 'Alert not found' })

res.status(200).json({
message: 'Alert successfully found',
body: alert.rows[0],
})
res.status(200).json({
message: 'Alert successfully found',
body: result.rows[0],
})
} catch (error) {
console.error(error)
res.status(500).json({
error: 'An error occured while getting alert',
})
}
},

CreateAlert: async (req, res) => {
const { message, type } = req.body

const newAlert = await db.query(
`INSERT INTO "Notification" ("message")
VALUES($1) RETURNING *;`,
[message]
)
createAlert: async (req, res) => {
try {
const { message, contentType } = req.body

if (!newAlert.rowCount)
return res.status(400).json({ error: 'Cannot Post' })
const result = await db.query(
`INSERT INTO "Notification" ("timestamp", "message", "contentType")
VALUES(NOW(), $1, $2) RETURNING *;`,
[message, contentType]
)

res.status(200).json({
message: 'Alert successfully created',
body: newAlert.rows[0],
})
res.status(200).json({
message: 'Alert successfully created',
body: result.rows[0],
})
} catch (error) {
console.error(error)
res.status(500).json({
error: 'An error occured while creating alert',
})
}
},

DeleteAlert: async (req, res) => {
const { id } = req.params

const Alerts = await db.query(`SELECT * FROM "Notification";`)

const alertsArr = Alerts.rows

if (!alertsArr.find((item) => item.NotificationId === Number(id)))
return res
.status(404)
.json({ error: 'Alert to be deleted not found' })
sendAlert: async (req, res) => {
try {
const { id } = req.params
const { sectorBaseName, sectorSuffixName } = req.body

let result

if (!sectorBaseName || !sectorSuffixName) {
// send alert to all captains
result = await db.query(
`INSERT INTO "RecieveNotification" ("notificationId", "captainId", "status")
SELECT $1, C."captainId", 'unread'
FROM "Captain" AS C
RETURNING *;`,
[id]
)
} else {
// send alert to all captains in sector
result = await db.query(
`INSERT INTO "RecieveNotification" ("notificationId", "captainId", "status")
SELECT $1, C."captainId", 'unread'
FROM "Captain" AS C
WHERE C."rSectorBaseName" = $2 AND
C."rSectorSuffixName" = $3
RETURNING *;`,
[id, sectorBaseName, sectorSuffixName]
)
}

res.status(200).json({
message: 'Alert successfully sent',
body: result.rows[0],
})
} catch (error) {
console.error(error)
res.status(500).json({
error: 'An error occured while sending alert',
})
}
},

deleteAlert: async (req, res) => {
try {
await db.query(
`DELETE FROM "Notification" WHERE "NotificationId" = $1;`,
const { id } = req.params
const result = await db.query(
`DELETE FROM "Notification" WHERE "notificationId" = $1 RETURNING *;`,
[id]
)

alertsArr.filter((item) => item.NotificationId !== Number(id))
return res.status(200).json({
message: 'Alert successfully deleted',
body: alertsArr,
body: result.rows[0],
})
} catch (error) {
console.error(error)
res.status(400).json({
res.status(500).json({
error: 'An error occured while deleting alert',
})
}
},

getAllAlerts: async (req, res) => {
const Alerts = await db.query(`SELECT * FROM "Notification";`)
try {
const { status, contentType } = req.body
const result = await db.query(
`SELECT N.*, R."status"
FROM "Notification" AS N, "RecieveNotification" AS R
WHERE N."notificationId" = R."notificationId" AND
R."captainId" = $1;`,
[req.captain.captainId]
)

res.status(200).json({
message: 'get Alerts successfully',
body: Alerts.rows,
})
let alerts = result.rows
if (status) {
alerts = alerts.filter((alert) => alert.status === status)
}
if (contentType) {
alerts = alerts.filter(
(alert) => alert.contentType === contentType
)
}

res.status(200).json({
message: 'get Alerts successfully',
body: alerts,
})
} catch (error) {
console.error(error)
res.status(500).json({
error: 'An error occured while getting alerts',
})
}
},
}

Expand Down
4 changes: 2 additions & 2 deletions server/controllers/captain.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ const captainController = {
getCaptain: async (req, res) => {
try {
// Extract the captain ID from the request params
const { captainId } = req.params
const { id } = req.params

// Query on the database to get that captain info
const result = await db.query(
`SELECT *
FROM "Captain"
WHERE "captainId" = $1`,
[captainId]
[id]
)

// If captain doesn't exist return an error message
Expand Down
11 changes: 4 additions & 7 deletions server/controllers/scout.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const scoutController = {
getAllScouts: async (req, res) => {
try {
const result = await db.query(`SELECT * FROM "Scout";`)

res.status(200).json({
message: 'Successful retrieval',
body: result.rows,
Expand Down Expand Up @@ -137,7 +136,6 @@ const scoutController = {
if (result1.rowCount == 0) {
return res.status(404).json({
error: 'No rows updated for the scout',
body: result1,
})
}

Expand All @@ -161,7 +159,7 @@ const scoutController = {
// Respond with the updated data
res.status(200).json({
message: 'Successful update',
body: { result1, result2 },
body: { scout: result1.rows[0], scoutProfile: result2.rows[0] },
})
} catch (error) {
console.log(error)
Expand Down Expand Up @@ -207,7 +205,6 @@ const scoutController = {
if (result1.rowCount == 0) {
return res.status(400).json({
error: 'No data was inserted for the scout',
body: result1,
})
}

Expand All @@ -222,22 +219,22 @@ const scoutController = {
schoolGrade,
photo,
birthCertificate,
result1.rows[0]['scoutId'],
result1.rows[0].scoutId,
]
)

// If nothing was inserted return an error
if (result2.rowCount == 0) {
return res.status(400).json({
error: 'No data was inserted for the scout profile',
body: result2,
body: { scout: result1.rows[0] },
})
}

// Return the data
res.status(200).json({
message: 'Successful insertion',
body: { result1, result2 },
body: { scout: result1.rows[0], scoutProfile: result2.rows[0] },
})
} catch (error) {
console.log(error)
Expand Down
17 changes: 9 additions & 8 deletions server/routes/alert.route.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {Router} from "express"
import alertController from "../controllers/alert.controller.js"
import { Router } from 'express'
import alertController from '../controllers/alert.controller.js'

const alertRouter = Router();
const alertRouter = Router()

alertRouter.get("/", alertController.getAllAlerts);
alertRouter.post("/", alertController.CreateAlert);
alertRouter.get("/:id", alertController.getAlert);
alertRouter.delete("/:id", alertController.DeleteAlert);
alertRouter.post('/', alertController.createAlert)
alertRouter.get('/:id', alertController.getAlert)
alertRouter.post('/:id', alertController.sendAlert)
alertRouter.delete('/:id', alertController.deleteAlert)
alertRouter.get('/', alertController.getAllAlerts)

export default alertRouter;
export default alertRouter
2 changes: 1 addition & 1 deletion server/routes/api.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ apiRouter.use('/stats', authMiddleware, statsRouter)
apiRouter.use('/finance', authMiddleware, financeRouter)
apiRouter.use('/term', authMiddleware, termRouter)
apiRouter.use('/captain', authMiddleware, captainRouter)
apiRouter.use('/alert', alertRouter)
apiRouter.use('/alert', authMiddleware, alertRouter)
apiRouter.use('/scout', authMiddleware, scoutRouter)

export default apiRouter
2 changes: 1 addition & 1 deletion server/routes/captain.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import captainController from '../controllers/captain.controller.js'
const captainRouter = Router()

captainRouter.get('/:id', captainController.getCaptain)
captainRouter.get('/all', captainController.getAllCaptains)
captainRouter.get('/', captainController.getAllCaptains)
captainRouter.get('/unit/:unitCaptainId', captainController.getCaptainsInUnit)
captainRouter.get(
'/sector/:baseName/:suffixName',
Expand Down
4 changes: 2 additions & 2 deletions server/routes/scout.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ const scoutRouter = Router()

scoutRouter.post('/', scoutController.insertScout)
scoutRouter.get('/:id', scoutController.getScout)
scoutRouter.put('/:id', scoutController.updateScout) // or patch
scoutRouter.get('/all', scoutController.getAllScouts)
scoutRouter.put('/:id', scoutController.updateScout)
scoutRouter.get('/', scoutController.getAllScouts)
scoutRouter.get('/unit/:unitCaptainId', scoutController.getScoutsInUnit)
scoutRouter.get(
'/sector/:baseName/:suffixName',
Expand Down