Skip to content

Commit

Permalink
fix: api for app update and insert
Browse files Browse the repository at this point in the history
  • Loading branch information
BharathSanjeeviT committed Feb 27, 2024
2 parents a8caab4 + 063135c commit f51e879
Show file tree
Hide file tree
Showing 13 changed files with 164 additions and 8,885 deletions.
8,846 changes: 0 additions & 8,846 deletions package-lock.json

This file was deleted.

56 changes: 49 additions & 7 deletions src/controllers/adminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
insertEvent,
addEventAdmin,
insertEvents4Admin,
getAdminEvents
getAdminEvents,
getUserCart,
createUserVIAadmin
} from "../queries/adminQueries.js";
import {
EventIdValidator,
Expand All @@ -26,7 +28,7 @@ import {
insertMissingOnes,
rollback,
} from "../queries/userQueries.js";
import { PostgresError } from "../interfaces/userInterface.js";
import { cartType, PostgresError } from "../interfaces/userInterface.js";

/* THIS IS THE ROUTE FOR TOGGLE THE USER TO BE PAID ON FRONT DESK
*/
Expand Down Expand Up @@ -152,16 +154,16 @@ const EventLogin = async (req: Request, res: Response, next: NextFunction) => {

/* FOR GETTING USERS FROM A PARTICULAR EVENT */
const GetUsersFromEvent = async (req: Request, res: Response) => {
if (!req.body.admin.is_event_admin) {
if (!req.body.admin.is_event_admin && (req.body.admin.events_id.includes(req.params.event_is))) {
return res
.status(401)
.json({ statusCode: 401, body: { message: "UnAuthorized Request" } });
}

const client = await pool.connect();
const { event_id } = EventIdValidator.parse(req.body);
const { event_id } = EventIdValidator.parse(req.params);
const data = await client.query(getUsersforEvent, [event_id]);

client.release()
return res.status(200).json({
statusCode: 200,
body: { message: "Sucessfull", data: data.rows },
Expand All @@ -182,6 +184,7 @@ const UpdateUserCart = async (req: Request, res: Response) => {
await client.query(insertMissingOnes, [user_email, events_id]);
await client.query(deleteFromCart, [user_email, events_id]);
await client.query(commit);
client.release()

return res.status(200).json({
statusCode: 200,
Expand All @@ -198,7 +201,10 @@ const UpdateUserCart = async (req: Request, res: Response) => {
.status(500)
.json({ statusCode: 500, body: { message: "Internal Server Error" } });
}
}
}else
return res
.status(403)
.json({ statusCode: 403, body: { message: "Not Authorized" } });
};

/*/
Expand Down Expand Up @@ -237,6 +243,40 @@ const EventAdminSignUp = async(req: Request, res: Response) => {
}
}

const GetUserCart = async(req: Request, res: Response) => {
if(req.body.admin.is_admin){
const {user_email} = req.body
const client = await pool.connect()
const data = await client.query(getUserCart, [user_email])
client.release()
let cartItems: Record<string, Array<cartType>> = {};
data.rows.forEach((event: cartType) => {
if (!cartItems[event.pass_id]) cartItems[event.pass_id] = [];
cartItems[event.pass_id].push(event);
});
return res
.status(200)
.json({ statusCode: 200, body: { data: cartItems } });
}else
return res
.status(403)
.json({ statusCode: 403, body: { message: "Admin not Authorized" } });
}

const CreateUser = async(req: Request, res:Response) => {
if(req.body.admin.is_admin){
const {email, name, clg_name, phone_no} = req.body
const client = await pool.connect()
await client.query(createUserVIAadmin,[name, email, phone_no, clg_name])
return res
.status(200)
.json({ statusCode: 200, body: { data: "User Created Sucessfully"} });
}else
return res
.status(403)
.json({ statusCode: 403, body: { message: "Admin not Authorized" } });
}

export {
UpdatePaid,
VerifyPaid,
Expand All @@ -246,5 +286,7 @@ export {
GetUsersFromEvent,
UpdateUserCart,
CreateEvent,
EventAdminSignUp
EventAdminSignUp,
GetUserCart,
CreateUser
};
30 changes: 30 additions & 0 deletions src/controllers/eventController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { Response, Request } from "express";
import { pool } from "../../config/db.js";
import {
createEvent,
editEvent
} from "../queries/eventQueries.js";

const CreateEvent = async (req: Request, res: Response) => {
if(req.body.admin.is_super_admin){
const { event_id, name, fee, pass_id} = req.body
const client = await pool.connect()
await client.query(createEvent, [event_id, name, fee, pass_id])
client.release()
return res
.status(200)
.json({ status: 200, body: { message: "Sucessfull" } });
Expand All @@ -18,6 +20,34 @@ const CreateEvent = async (req: Request, res: Response) => {
.json({ status: 403, body: { message: "Not Authorized" } });
};

const UpdateEvent = async (req: Request, res: Response) => {
if(req.body.admin.is_super_admin || (req.body.admin.events_id.includes(req.body.event_id))){
try{
const { event_id, name, fee, pass_id} = req.body
const client = await pool.connect()
const data = await client.query(editEvent, [event_id, name, fee, pass_id])
client.release()
if(data.rows.length == 1)
return res
.status(200)
.json({ status: 200, body: { message: "Updated Sucessfull" } });
else
return res
.status(500)
.json({ status: 500, body: { message: "Event doesnot exist" } });
} catch(err){
console.log(err)
return res
.status(500)
.json({ status: 500, body: { message: "Event not updated" } });
}
}else
return res
.status(403)
.json({ status: 403, body: { message: "Not Authorized" } });
};

export {
CreateEvent,
UpdateEvent
};
51 changes: 36 additions & 15 deletions src/controllers/sesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,21 +164,27 @@ const Registered = async (req: Request, res: Response) => {
<td colspan="4" style="font-family: monospace; vertical-align: center; padding: 2em">
<p>Hi ${name},
<br><br>
Congratulations! We are thrilled to inform you that your registration for Takshashila has been successfully received. We are delighted to have you as a participant in our upcoming college cultural extravaganza. To ensure a smooth and enjoyable experience for everyone, please take note of the following rules, regulations, and instructions:
Congratulations!
We are thrilled to inform you that your registration for Takshashila has been successfully received. We
are delighted to have you as a participant in our upcoming college cultural extravaganza. To ensure a
smooth and enjoyable experience for everyone, please take note of the following instructions:
<br><br>
<b>Rules and Regulations:</b>
<li><b>Punctuality:</b> Please arrive at least 30 minutes before the scheduled start time of your registered events.</li>
<li><b>Dress Code:</b> Ensure that you adhere to the specified dress code for each event. </li>
<li><b>Identification:</b> Carry a valid college ID card or any government-issued ID for verification purposes.</li>
<li>Payment for the event will be done only on-spot.</li>
<li>Please arrive at least 30 minutes before the scheduled start time of your registered events.</li>
<li>Kindly ensure that you adhere to all the eligibility criteria mentioned and the rules and
regulations of the registered event.</li>
<li>Participants are expected to conduct themselves professionally and ensure that you adhere to the
specified dress code for each event (if applicable).</li>
<li>Participants must compulsorily carry a valid college ID card for verification purposes.</li>
<li>Familiarize yourself with the event schedule and venue layout.</li>
<br>
If you have any specific requirements or concerns, please inform the event coordinators in advance.
Follow all safety protocols and guidelines provided by the event organizers at the venue. For any
queries or need any further assistance, feel free to reach out to our event coordinators.
We look forward to your enthusiastic participation and a memorable experience at Takshashila.
<br><br>
Best Regards,
<br>
<b>Instructions for Participants:</b>
<li>Familiarize yourself with the event schedule and venue layout.
<li>If you have any specific requirements or concerns, please inform the event coordinators in advance.
<li>Follow all safety protocols and guidelines provided by the event organizers on venue.
For any queries or need any further assistance, feel free to reach out to our event coordinators. Once again, congratulations on your successful registration! We look forward to your enthusiastic participation and a memorable experience at Takshashila.
Best Regards,
Takshashila team
</p>
</td>
Expand Down Expand Up @@ -365,8 +371,23 @@ const Sendotp = async (req: Request, res: Response) => {
<td>&nbsp;</td>
</tr>
<tr style="font-size: 1rem">
<td colspan="4" style="font-family: monospace; vertical-align: center; padding: 2em;text-align:center">
<p>Your OTP for Account Verification<br><br><b style="font-size:90px">${otp}</b></p>
<td colspan="4" style="font-family: monospace; vertical-align: center; padding: 2em;">
<p> Greetings,
<br><br>
Congratulations! 🎊 You're officially on the guest list for Takshashila – where knowledge meets laughter, and fun gets a degree in awesomeness! 🎓
To make sure it's really you and not just a very talented monkey with a typewriter who registered (hey, it happens), please verify with this One-Time Passcode (OTP)
<br><br>
<p style="text-align:center">
<b style="font-size:90px;">${otp}</b>
</p>
<br><br>
Once you're in, prepare to be dazzled by amazing minds, epic conversations, and maybe even a spontaneous dance-off (hey, it's been known to happen). 🕺
See you at Takshashila!
<br><br>
Cheers,
<br><br>
Team TK
</p>
</td>
</tr>
<tr style="vertical-align: top">
Expand Down
3 changes: 3 additions & 0 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const GetUserDetails = async (req: Request, res: Response) => {
const { email } = emailValidator.parse(req.body.user);
const client = await pool.connect();
const result = await client.query(getUserDetails, [email]);
client.release()
return res.status(200).json({
statusCode: 200,
body: { message: "Request Sucessfull", data: result.rows },
Expand Down Expand Up @@ -53,6 +54,7 @@ const GetUserCart = async (req: Request, res: Response) => {
const { email } = emailValidator.parse(req.body.user);
const client = await pool.connect();
const data = await client.query(getCart, [email]);
client.release()
let cartItems: Record<string, Array<cartType>> = {};
data.rows.forEach((event: cartType) => {
if (!cartItems[event.pass_id]) cartItems[event.pass_id] = [];
Expand All @@ -78,6 +80,7 @@ const UpdateUserCart = async (
await client.query(insertMissingOnes, [email, events_id]);
await client.query(deleteFromCart, [email, events_id]);
await client.query(commit);
client.release()

return res.status(200).json({
statusCode: 200,
Expand Down
10 changes: 5 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import cors from "cors";
import { PORT } from "../config/port.js";
import { Admin, Events, Users, Support } from "./routes/index.js";
import errorHandler from "./middlewares/errorHandler.js";
import { AuthourizeUser, AuthourizeAdmin } from "./middlewares/authHandler.js";
import { AuthourizeAdmin, AuthourizeUser } from "./middlewares/authHandler.js";
import serverless from "serverless-http";

const app = express();
Expand Down Expand Up @@ -31,8 +31,8 @@ app.use(Support.BASE_ROUTE, Support.router);

app.use(errorHandler);

app.listen(PORT, () => {
console.log(`PORT RUNNING ON ${PORT}`);
});
// app.listen(PORT, () => {
// console.log(`PORT RUNNING ON ${PORT}`);
// });

// export const handler = serverless(app);
export const handler = serverless(app);
6 changes: 5 additions & 1 deletion src/middlewares/authHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ export const CreateEventAdminToken = async (req: Request, res: Response) => {
const token: string = jwt.sign(tokenData, SECRET);
return res.status(200).json({
statusCode: 200,
body: { message: "Token Generated Sucessfully", token: token },
body: { message: "Token Generated Sucessfully",
token: token ,
event: req.body.events_id,
isAdmin: (req.body.events_id.length === 0)
},
});
};
2 changes: 1 addition & 1 deletion src/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function errorHandler(
},
});
}

console.log(err)
return res.status(500).json({
statusCode: 500,
body: {
Expand Down
17 changes: 16 additions & 1 deletion src/queries/adminQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const insertAdmin: string =
"INSERT INTO admin (uname, password) VALUES ($1, $2)";
export const getAdminPassword: string =
"SELECT password FROM admin WHERE uname = $1";
export const getUsersforEvent: string = `select u.name, u.phone_no, u.clg_name, ue.is_present, ue.paid from users u join
export const getUsersforEvent: string = `select u.name, u.phone_no, u.clg_name, ue.is_present, ue.paid, u.email from users u join
users_events ue on ue.user_email = u.email where ue.event_id = $1`;
export const insertEvent: string = `insert into events (name, id, fee, pass_id, password) values
($1, $2, $3, $4, $5)`;
Expand All @@ -17,3 +17,18 @@ export const insertEvents4Admin: string = `
ON CONFLICT (admin_id, event_id) DO NOTHING`;
export const getEventAdminPassword: string = `SELECT password FROM event_admin WHERE id = $1`;
export const getAdminEvents: string = `SELECT event_id FROM admin_events WHERE admin_id = $1`;
export const getUserCart: string = `
SELECT
ue.event_id,
e.name,
e.fee,
ue.paid,
ue.is_present,
p.id AS pass_id,
ue.user_email
FROM users_events ue
JOIN events e ON ue.event_id = e.id
JOIN pass p ON e.pass_id = p.id
WHERE ue.user_email= $1;
`;
export const createUserVIAadmin: string = `INSERT INTO users (name,email,phone_no,clg_name) VALUES ($1,$2,$3,$4)`
7 changes: 6 additions & 1 deletion src/queries/eventQueries.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
export const createEvent: string = `INSERT INTO
events (id, name, fee, pass_id) VALUES ($1, $2, $3, $4)`;
events (id, name, fee, pass_id) VALUES ($1, $2, $3, $4)`;
export const editEvent: string = `UPDATE events SET
name = $2,
fee = $3,
pass_id = $4
WHERE id = $1 returning *`;
16 changes: 10 additions & 6 deletions src/routes/adminRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import {
GetUsersFromEvent,
UpdateUserCart,
CreateEvent,
EventAdminSignUp
EventAdminSignUp,
GetUserCart,
CreateUser
} from "../controllers/adminController.js";
import asyncMiddleware from "../middlewares/asyncMiddleware.js";
import {
Expand All @@ -23,14 +25,16 @@ const BASE_ROUTE = "/admin";

router.put("/pay-event", AuthourizeAdmin, asyncMiddleware(UpdatePaid));
router.put("/update-cart", AuthourizeAdmin, asyncMiddleware(UpdateUserCart));
router.post("/get-cart", AuthourizeAdmin, asyncMiddleware(GetUserCart))
router.post("/create-user", AuthourizeAdmin, asyncMiddleware(CreateUser))

router.put("/allow", AuthourizeAdmin, asyncMiddleware(VerifyPaid));
router.get("/get-users", AuthourizeAdmin, asyncMiddleware(GetUsersFromEvent));
router.get("/get-users/:event_id", AuthourizeAdmin, asyncMiddleware(GetUsersFromEvent));

//Comment this while PRODUCTION
router.post("/signup", asyncMiddleware(UserSignUp));
router.post("/event/signup", asyncMiddleware(EventAdminSignUp));
router.post("/create-event", asyncMiddleware(CreateEvent))
// Comment this while PRODUCTION
// router.post("/signup", asyncMiddleware(UserSignUp));
// router.post("/event/signup", asyncMiddleware(EventAdminSignUp));
// router.post("/create-event", asyncMiddleware(CreateEvent))

router.post("/login", asyncMiddleware(UserLogIn), CreateAdminToken);
router.post("/event/login", asyncMiddleware(EventLogin), CreateEventAdminToken);
Expand Down
3 changes: 2 additions & 1 deletion src/routes/eventsRoute.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import express from "express";
import { Module } from "../../libs/utils/types/module.js";
import { CreateEvent } from "../controllers/eventController.js";
import { CreateEvent, UpdateEvent } from "../controllers/eventController.js";
import asyncMiddleware from "../middlewares/asyncMiddleware.js";

const router = express.Router();
const BASE_ROUTE = "/events";

router.post("/", asyncMiddleware(CreateEvent));
router.put("/", asyncMiddleware(UpdateEvent));

const MODULE: Module = {
router,
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*", "./jest.config.ts"]
"include": ["src/**/*", "./jest.config.ts", "api/*"]
}

0 comments on commit f51e879

Please sign in to comment.