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

Backend/fix/itineraries #75

Merged
merged 2 commits into from
Nov 11, 2024
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
1 change: 1 addition & 0 deletions backend/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const LOYALTY_POINT_GAIN = 600000;
8 changes: 6 additions & 2 deletions backend/src/controllers/booking.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import { logger } from '../middlewares/logger.middleware';
import Validator from '../utils/Validator.utils';
import bookingRepo from '../database/repositories/booking.repo';
import { checkUserLegalAge } from '../utils/AgeVerification.utils';
import userRepo from '../database/repositories/user.repo';
import { LOYALTY_POINT_GAIN } from '../constants';

class BookingController {
async bookItinerary(req: Request, res: Response) {
try {
Validator.validateId(req.body.itinerary_id, 'incorrect itinerary id');

if (!(await checkUserLegalAge(req.user.userId))) {
res.status(403).json({ message: 'Cannot book as user is under 18' });
res.status(ResponseStatusCodes.FORBIDDEN).json({ message: 'Cannot book as user is under 18' });
return;
}
const booking = await bookingRepo.bookItinerary(req.user.userId, req.body.itinerary_id);
await userRepo.updateUserLoyaltyPoints(req.user.userId, LOYALTY_POINT_GAIN);

const response = {
message: 'Booking successful',
Expand All @@ -35,11 +38,12 @@ class BookingController {
Validator.validateId(req.body.activity_id, 'incorrect activity id');

if (!(await checkUserLegalAge(req.user.userId))) {
res.status(403).json({ message: 'Cannot book as user is under 18' });
res.status(ResponseStatusCodes.FORBIDDEN).json({ message: 'Cannot book as user is under 18' });
return;
}

const booking = await bookingRepo.bookActivity(req.user.userId, req.body.activity_id);
await userRepo.updateUserLoyaltyPoints(req.user.userId, LOYALTY_POINT_GAIN);

const response = {
message: 'Booking successful',
Expand Down
19 changes: 1 addition & 18 deletions backend/src/controllers/loyalty.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,11 @@ async function redeemPoints(req: Request, res: Response) {

if (!user) throw new Error('User not found');

if (user.loyalty_points < points) {
throw new Error('Insufficient points');
}

user.loyalty_points -= points;
user.loyalty_level = getLoyaltyLevel(user.loyalty_points);
user.wallet += points * 0.01;

// Update user
await userRepo.updateUser(userId, user as UserType);
await userRepo.updateUserLoyaltyPoints(userId, -points);

res.status(ResponseStatusCodes.OK).json({ message: 'Points redeemed successfully' });
} catch (error: any) {
Expand All @@ -32,16 +27,4 @@ async function redeemPoints(req: Request, res: Response) {
}
}

function getLoyaltyLevel(points: number): number {
let level: number = 1;

if (points >= 1000000) {
level = 3;
} else if (points >= 500000) {
level = 2;
}

return level;
}

export { redeemPoints };
18 changes: 18 additions & 0 deletions backend/src/controllers/users/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ const updateUser = async (req: Request, res: Response) => {
const requestAccountDeletion = async (req: Request, res: Response) => {
try {
const userId: string = req.user.userId;

const userItineraryBookings = await userRepo.getItinerary(userId);
const unattendedItineraryBookings =
userItineraryBookings?.itinerary_bookings.filter((booking: any) =>
['pending', 'confirmed'].includes(booking.status)
) || [];

const userActivityBookings = await userRepo.getItinerary(userId);
const unattendedActivityBookings =
userActivityBookings?.activity_bookings.filter((booking: any) =>
['pending', 'confirmed'].includes(booking.status)
) || [];

if (unattendedItineraryBookings.length > 0 || unattendedActivityBookings.length > 0) {
res.status(ResponseStatusCodes.BAD_REQUEST).json({ message: 'You have unattended bookings' });
return;
}

await userRepo.requestAccountDeletion(userId);
const response = {
message: 'Account deletion requested successfully',
Expand Down
18 changes: 18 additions & 0 deletions backend/src/database/repositories/user.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ObjectId } from 'mongodb';
import { User } from '../models/user.model';
import { UserType } from '../../types/User.types';
import { accountType } from '../../types/User.types';
import getUserLevel from '../../utils/UserLevel.util';

class UserRepository {
async getUsers() {
Expand Down Expand Up @@ -36,6 +37,23 @@ class UserRepository {
return await User.updateOne({ _id: new ObjectId(id) }, user);
}

async updateUserLoyaltyPoints(id: string, points: number) {
const user = await this.findUserById(id);
const oldPoints = user?.loyalty_points ?? 0;
const newPoints = oldPoints + points;

if (newPoints < 0) {
throw new Error('Insufficient points');
}

return await User.findByIdAndUpdate(id, {
$set: {
loyalty_points: newPoints,
loyalty_level: getUserLevel(newPoints),
},
});
}

async acceptUser(id: string) {
return await User.updateOne({ _id: new ObjectId(id) }, { accepted: true });
}
Expand Down
4 changes: 3 additions & 1 deletion backend/tests/itinerary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ let activityRef = {

let newItinerary: ItineraryType = {
name: 'Test Itinerary',
category: 'Test Category',
category: '',
tags: [],
activities: [],
locations: [location],
Expand Down Expand Up @@ -92,6 +92,8 @@ describe('Itinerary tests', () => {
activityRef.activity = newActivity.body.data.activityId;
newItinerary.tags.push(newTag.body.data.tagId);
newItinerary.activities.push(activityRef);
newItinerary.category = newCategory.body.data.categoryId;

const response = await requestWithAuth('post', '/api/itineraries').send(newItinerary);

itineraryId = response.body.data.itineraryId;
Expand Down
Loading