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

put events-router #69

Merged
merged 19 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import morgan from "morgan";
import bodyParser from "body-parser";
import errorHandler from "./middleware/error-handler";

import attendeeRouter from "./services/attendees/attendee-router";
import attendeeRouter from "./services/attendee/attendee-router";
import authRouter from "./services/auth/auth-router";
import eventsRouter from "./services/events/events-router";
import notificationsRouter from "./services/notifications/notifications-router";
Expand Down
24 changes: 21 additions & 3 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ import mongoose, { Schema, Document } from "mongoose";
import {
AttendeeSchema,
AttendeeValidator,
} from "./services/attendees/attendee-schema";
import { RoleValidator, RoleSchema } from "./services/auth/auth-schema";
} from "./services/attendee/attendee-schema";
import {
AttendeeAttendanceSchema,
AttendeeAttendanceValidator,
} from "./services/attendee/attendee-schema";
import {
EventSchema,
privateEventValidator,
} from "./services/events/events-schema";
import {
EventAttendanceSchema,
EventAttendanceValidator,
} from "./services/events/events-schema";
import { RoleValidator, RoleSchema } from "./services/auth/auth-schema";
import {
RegistrationSchema,
RegistrationValidator,
Expand Down Expand Up @@ -55,12 +63,22 @@ function initializeModel(
export const Database = {
ROLES: initializeModel("roles", RoleSchema, RoleValidator),
EVENTS: initializeModel("events", EventSchema, privateEventValidator),
EVENTS_ATTENDANCE: initializeModel(
"events_attendance",
EventAttendanceSchema,
EventAttendanceValidator
),
ATTENDEE: initializeModel("attendee", AttendeeSchema, AttendeeValidator),
ATTENDEE_ATTENDANCE: initializeModel(
"attendee_attendance",
AttendeeAttendanceSchema,
AttendeeAttendanceValidator
),
SUBSCRIPTIONS: initializeModel(
"subscriptions",
SubscriptionSchema,
SubscriptionSchemaValidator
),
ATTENDEES: initializeModel("attendees", AttendeeSchema, AttendeeValidator),
REGISTRATION: initializeModel(
"registration",
RegistrationSchema,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Database } from "../../database";
import RoleChecker from "../../middleware/role-checker";
import { Role } from "../auth/auth-models";
import dotenv from "dotenv";
import { generateQrHash } from "./attendees-utils";
import { generateQrHash } from "./attendee-utils";

dotenv.config();

Expand All @@ -15,7 +15,7 @@ const attendeeRouter = Router();
attendeeRouter.post("/", async (req, res, next) => {
try {
const attendeeData = AttendeeValidator.parse(req.body);
const attendee = new Database.ATTENDEES(attendeeData);
const attendee = new Database.ATTENDEE(attendeeData);
await attendee.save();

return res.status(StatusCodes.CREATED).json(attendeeData);
Expand Down Expand Up @@ -51,7 +51,7 @@ attendeeRouter.get(
const userId = payload.userId;

// Check if the user exists in the database
const user = await Database.ATTENDEES.findOne({ userId });
const user = await Database.ATTENDEE.findOne({ userId });

if (!user) {
return res
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import mongoose from "mongoose";
import { Schema } from "mongoose";
import { z } from "zod";

// Zod schema for attendee
const AttendeeValidator = z.object({
export const AttendeeValidator = z.object({
userId: z.string(),
name: z.string(),
email: z.string().email(),
Expand All @@ -21,17 +21,17 @@ const AttendeeValidator = z.object({
});

// Mongoose schema for attendee
const AttendeeSchema = new mongoose.Schema({
export const AttendeeSchema = new Schema({
userId: { type: String, required: true, unique: true },
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
events: [{ type: mongoose.Schema.Types.ObjectId, ref: "Event" }],
events: [{ type: Schema.Types.ObjectId, ref: "Event" }],
dietaryRestrictions: { type: [String], required: true },
allergies: { type: [String], required: true },
hasCheckedIn: { type: Boolean, default: false },
points: { type: Number, default: 0 },
hasPriority: {
type: new mongoose.Schema(
type: new Schema(
{
dayOne: { type: Boolean, default: false },
dayTwo: { type: Boolean, default: false },
Expand All @@ -45,4 +45,16 @@ const AttendeeSchema = new mongoose.Schema({
},
});

export { AttendeeSchema, AttendeeValidator };
export const AttendeeAttendanceSchema = new Schema({
userId: {
type: String,
ref: "Attendee",
required: true,
},
eventsAttended: [{ type: String, ref: "Event", required: true }],
});

export const AttendeeAttendanceValidator = z.object({
userId: z.string(),
eventsAttended: z.array(z.string()),
});
52 changes: 44 additions & 8 deletions src/services/events/events-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Router } from "express";
import { StatusCodes } from "http-status-codes";
import { publicEventValidator } from "./events-schema";
import { Database } from "../../database";
import { checkInUserToEvent } from "./events-utils";
// import {mongoose} from "mongoose";

const eventsRouter = Router();

Expand All @@ -26,6 +28,21 @@ eventsRouter.get("/currentOrNext", async (req, res, next) => {
}
});

eventsRouter.get("/:EVENTID", async (req, res, next) => {
riyap marked this conversation as resolved.
Show resolved Hide resolved
const eventId = req.params.EVENTID;
try {
const event = await Database.EVENTS.findOne({ eventId: eventId });
if (!event) {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: "DoesNotExist" });
}
return res.status(StatusCodes.OK).json(event.toObject());
riyap marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
next(error);
}
});

eventsRouter.post("/", async (req, res, next) => {
try {
const validatedData = publicEventValidator.parse(req.body);
Expand All @@ -37,22 +54,22 @@ eventsRouter.post("/", async (req, res, next) => {
}
});

eventsRouter.get("/:EVENTID", async (req, res, next) => {
eventsRouter.put("/:EVENTID", async (req, res, next) => {
AydanPirani marked this conversation as resolved.
Show resolved Hide resolved
const eventId = req.params.EVENTID;
try {
const unfiltered_event = await Database.EVENTS.findOne({
eventId: eventId,
});
const validatedData = publicEventValidator.parse(req.body);
riyap marked this conversation as resolved.
Show resolved Hide resolved
const event = await Database.EVENTS.findOneAndUpdate(
{ eventId: eventId },
{ $set: validatedData }
);

if (!unfiltered_event) {
if (!event) {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: "DoesNotExist" });
}

const filtered_event = publicEventValidator.parse(unfiltered_event);

return res.status(StatusCodes.OK).json(filtered_event);
return res.sendStatus(StatusCodes.OK);
} catch (error) {
next(error);
}
Expand All @@ -75,6 +92,7 @@ eventsRouter.get("/", async (req, res, next) => {
eventsRouter.delete("/:EVENTID", async (req, res, next) => {
const eventId = req.params.EVENTID;
try {
// const objectId = mongoose.Types.ObjectId(eventId)
await Database.EVENTS.findOneAndDelete({ eventId: eventId });

return res.sendStatus(StatusCodes.NO_CONTENT);
Expand All @@ -83,4 +101,22 @@ eventsRouter.delete("/:EVENTID", async (req, res, next) => {
}
});

eventsRouter.post("/check-in", async (req, res, next) => {
try {
const { eventId, userId } = req.body;
const result = await checkInUserToEvent(eventId, userId);
if (result.success) {
return res
.status(StatusCodes.OK)
.json({ message: "Check-in successful" });
} else {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: result.message });
}
riyap marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
next(error);
}
});

export default eventsRouter;
22 changes: 21 additions & 1 deletion src/services/events/events-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { v4 as uuidv4 } from "uuid";
export const EventType = z.enum(["A", "B", "C"]);

export const publicEventValidator = z.object({
eventId: z.coerce.string(),
eventId: z.coerce.string().optional(),
name: z.string(),
startTime: z.coerce.date(),
endTime: z.coerce.date(),
Expand Down Expand Up @@ -70,3 +70,23 @@ export const EventSchema = new Schema({
enum: EventType.Values,
},
});

export const EventAttendanceSchema = new Schema({
eventId: {
type: String,
ref: "Event",
required: true,
},
attendees: [
{
type: String,
ref: "Attendee",
required: true,
},
],
});

export const EventAttendanceValidator = z.object({
eventId: z.string(),
attendees: z.array(z.string()),
});
37 changes: 37 additions & 0 deletions src/services/events/events-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Database } from "../../database";

export async function checkInUserToEvent(eventId: string, userId: string) {
// Check if the event and attendee exist
const [event, attendee] = await Promise.all([
riyap marked this conversation as resolved.
Show resolved Hide resolved
Database.EVENTS.findOne({ eventId }),
Database.ATTENDEE.findOne({ userId }),
]);

console.log(event);
console.log(attendee);
riyap marked this conversation as resolved.
Show resolved Hide resolved
if (!event || !attendee) {
return { success: false, message: "Event or Attendee not found" };
riyap marked this conversation as resolved.
Show resolved Hide resolved
}

try {
// Check or create event attendance record
const eventAttendance = Database.EVENTS_ATTENDANCE.findOneAndUpdate(
{ eventId: eventId },
{ $addToSet: { attendees: userId } },
{ new: true, upsert: true }
);

// Check or create attendee attendance record
const attendeeAttendance =
Database.ATTENDEE_ATTENDANCE.findOneAndUpdate(
{ userId: userId },
{ $addToSet: { eventsAttended: eventId } },
{ new: true, upsert: true }
);

await Promise.all([eventAttendance, attendeeAttendance]);
return { success: true };
} catch (error) {
return { success: false, message: "couldn't upsert event or attendee" };
riyap marked this conversation as resolved.
Show resolved Hide resolved
}
}
4 changes: 2 additions & 2 deletions src/services/registration/registration-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { RegistrationValidator } from "./registration-schema";
import { Database } from "../../database";
import RoleChecker from "../../middleware/role-checker";
import { Role } from "../auth/auth-models";
import { AttendeeValidator } from "../attendees/attendee-schema";
import { AttendeeValidator } from "../attendee/attendee-schema";
import { registrationExists } from "./registration-utils";

const registrationRouter = Router();
Expand Down Expand Up @@ -78,7 +78,7 @@ registrationRouter.post("/submit", RoleChecker([]), async (req, res, next) => {

const attendeeData = AttendeeValidator.parse(registrationData);

await Database.ATTENDEES.findOneAndUpdate(
await Database.ATTENDEE.findOneAndUpdate(
{ userId: payload.userId },
attendeeData,
{ upsert: true, setDefaultsOnInsert: true }
Expand Down
18 changes: 9 additions & 9 deletions src/services/stats/stats-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ statsRouter.get(
RoleChecker([Role.enum.STAFF], false),
async (req, res, next) => {
try {
const attendees = await Database.ATTENDEES.find({
const attendees = await Database.ATTENDEE.find({
events: { $ne: [] },
});

Expand All @@ -35,7 +35,7 @@ statsRouter.get(
.status(StatusCodes.BAD_REQUEST)
.json({ error: "MissingPriceParameter" });
}
const attendees = await Database.ATTENDEES.find({
const attendees = await Database.ATTENDEE.find({
points: { $gte: price },
});

Expand All @@ -52,7 +52,7 @@ statsRouter.get(
RoleChecker([Role.enum.STAFF], false),
async (req, res, next) => {
try {
const attendees = await Database.ATTENDEES.find({
const attendees = await Database.ATTENDEE.find({
hasCheckedIn: true,
});

Expand Down Expand Up @@ -102,23 +102,23 @@ statsRouter.get(
async (req, res, next) => {
try {
const results = await Promise.allSettled([
Database.ATTENDEES.countDocuments({
Database.ATTENDEE.countDocuments({
allergies: { $size: 0 },
dietaryRestrictions: { $size: 0 },
}),
Database.ATTENDEES.countDocuments({
Database.ATTENDEE.countDocuments({
allergies: { $size: 0 },
dietaryRestrictions: { $ne: [] },
}),
Database.ATTENDEES.countDocuments({
Database.ATTENDEE.countDocuments({
allergies: { $ne: [] },
dietaryRestrictions: { $size: 0 },
}),
Database.ATTENDEES.countDocuments({
Database.ATTENDEE.countDocuments({
allergies: { $ne: [] },
dietaryRestrictions: { $ne: [] },
}),
Database.ATTENDEES.aggregate([
Database.ATTENDEE.aggregate([
{
$unwind: "$allergies",
},
Expand All @@ -129,7 +129,7 @@ statsRouter.get(
},
},
]),
Database.ATTENDEES.aggregate([
Database.ATTENDEE.aggregate([
{
$unwind: "$dietaryRestrictions",
},
Expand Down