Skip to content

Commit

Permalink
feat: implement get tourist's purchased products endpoint
Browse files Browse the repository at this point in the history
- minor fix in check if booked before deleting itinerary
- refactor code
  • Loading branch information
yousefyasser committed Nov 9, 2024
1 parent 0961598 commit 369fb1f
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 13 deletions.
4 changes: 4 additions & 0 deletions backend/src/controllers/itinerary.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { accountType } from '../types/User.types';
import ItineraryRepo from '../database/repositories/itinerary.repo';
import BookingRepo from '../database/repositories/booking.repo';
import currencyConverterService from '../services/currencyConverter';
import Validator from '../utils/Validator.utils';

const getItineraries = async (req: Request, res: Response) => {
try {
Expand Down Expand Up @@ -112,8 +113,11 @@ const deleteItinerary = async (req: Request, res: Response) => {
try {
const ItineraryId: string = req.params.id;

Validator.validateId(ItineraryId, 'Invalid itinerary ID');

if (await BookingRepo.checkItineraryBooked(ItineraryId)) {
res.status(ResponseStatusCodes.FORBIDDEN).json({ message: 'Cannot delete Itinerary as it is already booked' });
return;
}
const deleteRes = await ItineraryRepo.deleteItinerary(ItineraryId);
const response = {
Expand Down
8 changes: 6 additions & 2 deletions backend/src/controllers/product.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { logger } from '../middlewares/logger.middleware';
import { ResponseStatusCodes } from '../types/ResponseStatusCodes.types';
import { range } from '../utils/Rangify.utils';
import { generateRanges } from '../utils/Rangify.utils';
import { ProductType } from '../types/Product.types';

import productRepo from '../database/repositories/product.repo';
import { ReviewType } from '../types/Review.types';
import currencyConverterService from '../services/currencyConverter';
import userRepo from '../database/repositories/user.repo';

const findProductById = async (req: Request, res: Response) => {
try {
Expand Down Expand Up @@ -255,15 +254,20 @@ async function buyProduct(req: Request, res: Response) {
const productId = req.params.id;
const quantity = parseInt(req.body.quantity);
const product = await productRepo.getProductById(productId);

if (!product) {
res.status(ResponseStatusCodes.NOT_FOUND).json({ message: 'Product not found', data: [] });
return;
}

if (product.available_quantity && product.available_quantity < quantity) {
res.status(ResponseStatusCodes.BAD_REQUEST).json({ message: 'Insufficient quantity', data: [] });
return;
}

await productRepo.buyProduct(productId, quantity);
await userRepo.buyProduct(req.user.userId, productId);

res.status(ResponseStatusCodes.OK).json({ message: 'Product bought successfully', data: { productId, quantity } });
} catch (error: any) {
logger.error(`Error buying product: ${error.message}`);
Expand Down
15 changes: 15 additions & 0 deletions backend/src/controllers/users/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,20 @@ const cancelItineraryBooking = async (req: Request, res: Response) => {
}
};

const getPurchasedProducts = async (req: Request, res: Response) => {
try {
const user = await userRepo.getUserWithPurchasedProducts(req.user.userId);

res.status(ResponseStatusCodes.OK).json({
message: 'Purchased products fetched successfully',
data: { purchased_products: user?.purchased_products },
});
} catch (error: any) {
logger.error(`Error fetching purchased products: ${error.message}`);
res.status(ResponseStatusCodes.BAD_REQUEST).json({ message: error.message, data: [] });
}
};

export {
getUsers,
deleteUser,
Expand All @@ -292,4 +306,5 @@ export {
getActivity,
cancelActivityBooking,
cancelItineraryBooking,
getPurchasedProducts,
};
5 changes: 4 additions & 1 deletion backend/src/database/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const companyProfileSchema = new mongoose.Schema({
type: String,
required: true,
},
specialities: {
specialties: {
type: String,
},
});
Expand Down Expand Up @@ -142,6 +142,9 @@ const userSchema = new mongoose.Schema(
activity_bookings: {
type: [{ type: Schema.Types.ObjectId, ref: 'booking' }],
},
purchased_products: {
type: [{ type: Schema.Types.ObjectId, ref: 'product' }],
},
modified_by: {
type: Schema.Types.ObjectId,
ref: 'user',
Expand Down
4 changes: 2 additions & 2 deletions backend/src/database/repositories/booking.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ class BookingRepo {
}

async checkItineraryBooked(itineraryId: string): Promise<boolean> {
const booking = await Booking.find({ itineraryId: itineraryId });
const booking = await Booking.find({ itinerary: itineraryId });

return !!booking;
return booking.length > 0;
}
}

Expand Down
3 changes: 0 additions & 3 deletions backend/src/database/repositories/itinerary.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ class ItineraryRepo {
}

async deleteItinerary(id: string) {
Validator.validateId(id, 'Invalid itinerary ID');
return await Itinerary.deleteOne({ _id: new ObjectId(id) });
}

Expand All @@ -46,8 +45,6 @@ class ItineraryRepo {
await Itinerary.findByIdAndUpdate(id, { active: active });
}



async getItineraryStartDate(id: string) {
return await Itinerary.findById(id).select('timeline');
}
Expand Down
13 changes: 9 additions & 4 deletions backend/src/database/repositories/user.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ class UserRepository {
.populate('preferences');
}

async getUserWithPurchasedProducts(id: string) {
return await User.findById(id).populate('purchased_products');
}

async createUser(user: UserType) {
const userRes = await User.create(user);
return userRes;
Expand Down Expand Up @@ -93,10 +97,11 @@ class UserRepository {
}

async cancelItineraryBooking(id: string, booking_id: string) {
return await User.updateOne(
{ _id: new ObjectId(id) },
{ $pull: { itinerary_bookings: new ObjectId(booking_id) } }
);
return await User.updateOne({ _id: new ObjectId(id) }, { $pull: { itinerary_bookings: new ObjectId(booking_id) } });
}

async buyProduct(id: string, product_id: string) {
return await User.findByIdAndUpdate(id, { $push: { purchased_products: new ObjectId(product_id) } });
}
}

Expand Down
5 changes: 5 additions & 0 deletions backend/src/routes/user.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
getActivity,
cancelActivityBooking,
cancelItineraryBooking,
getPurchasedProducts,
} from '../controllers/users/user.controller';

const router = Router();
Expand All @@ -35,10 +36,14 @@ router.use('/tourists', touristRouter);
router.get('/', getUsers);
router.post('/', createUser);
router.patch('/requestDeletion', requestAccountDeletion);

router.get('/purchasedProducts', getPurchasedProducts);

router.get('/getItineraries', getItinerary);
router.get('/getActivities', getActivity);
router.patch('/cancelActivityBooking', cancelActivityBooking);
router.patch('/cancelItineraryBooking', cancelItineraryBooking);

router.patch('/changePassword', ChangeUserPassword);
router.patch('/accept-user/:id', acceptUser);
router.patch('/acceptTerms', acceptTerms);
Expand Down
3 changes: 2 additions & 1 deletion backend/src/types/User.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface previousWorkType {
export interface companyProfileType {
industry: string;
headquarters: string;
specialities?: string;
specialties?: string;
}

export interface UserType {
Expand Down Expand Up @@ -57,4 +57,5 @@ export interface UserType {
loyalty_points: number;
wallet?: number;
itinerary_bookings: [Types.ObjectId];
purchased_products: [Types.ObjectId];
}

0 comments on commit 369fb1f

Please sign in to comment.