Skip to content

Commit

Permalink
create reservation working changes
Browse files Browse the repository at this point in the history
  • Loading branch information
udaysingh236 committed Jul 30, 2023
1 parent 71ab064 commit 72cec7d
Show file tree
Hide file tree
Showing 11 changed files with 469 additions and 66 deletions.
46 changes: 27 additions & 19 deletions docs/playground-2.mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ use('kutir_data');
// { upsert: true }
// );

for (let index = 1; index <= 20; index++) {
db.roomavls.insertOne({
hotelId: 1,
roomId: index,
reservations: []
});
}

// db.reservations.insertMany([
// {
// roomNum: 1,
Expand All @@ -41,23 +49,23 @@ use('kutir_data');
// }
// ]);

const fromDate = new Date('2023-07-23');
const toDate = new Date('2023-07-25');
// const fromDate = new Date('2023-07-23');
// const toDate = new Date('2023-07-25');

db.roomavls.aggregate([
{
$match: {
reservations: {
$not: {
$elemMatch: {
restoDate: { $gt: fromDate },
resfromDate: { $lt: toDate }
}
}
}
}
},
{
$lookup: { from: 'rooms', localField: 'roomId', foreignField: '_id', as: 'roomsInfo' }
}
]);
// db.roomavls.aggregate([
// {
// $match: {
// reservations: {
// $not: {
// $elemMatch: {
// restoDate: { $gt: fromDate },
// resfromDate: { $lt: toDate }
// }
// }
// }
// }
// },
// {
// $lookup: { from: 'rooms', localField: 'roomId', foreignField: '_id', as: 'roomsInfo' }
// }
// ]);
4 changes: 3 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import employeeRouter from './routes/employee';
import couponRouter from './routes/coupons';
import voucherRouter from './routes/vouchers';
import rateRouter from './routes/rates';
import availbilityRouter from './routes/availbility';
import availbilityRouter from './routes/availability';
import reservationRouter from './routes/reservation';
import swaggerDocs from './utils/swagger';
const app = express();
const port = process.env.port || 3000;
Expand All @@ -23,5 +24,6 @@ app.use('/v1/hotels', couponRouter);
app.use('/v1/hotels', voucherRouter);
app.use('/v1/hotels', rateRouter);
app.use('/v1/hotels', availbilityRouter);
app.use('/v1/hotels', reservationRouter);

export default app;
6 changes: 3 additions & 3 deletions src/controllers/availability.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Availability, { IAvailability } from '../models/availability.models';
import Availability, { IAvailabilityWithRooms } from '../models/availability.models';
import { logger } from '../utils/logger';
import { IAvailabilityData } from '../types/controller.types';

Expand All @@ -7,7 +7,7 @@ export async function getAllAvailableRooms(
fromDate: string,
toDate: string
): Promise<IAvailabilityData> {
const availabilityData: Array<IAvailability> = await Availability.aggregate()
const availabilityData: Array<IAvailabilityWithRooms> = await Availability.aggregate()
.match({
hotelId: hotelId,
reservations: {
Expand Down Expand Up @@ -40,7 +40,7 @@ export async function getAvailbilityByRoom(
fromDate: string,
toDate: string
): Promise<IAvailabilityData> {
const availabilityData: Array<IAvailability> = await Availability.aggregate()
const availabilityData: Array<IAvailabilityWithRooms> = await Availability.aggregate()
.match({
hotelId: hotelId,
roomId: roomId,
Expand Down
94 changes: 64 additions & 30 deletions src/controllers/reservation.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
IReservationsPayload,
IRateShopResponse,
IRateShopSchema,
IReservationSchema
IReservationSchema,
IAvailabilityData
} from '../types/controller.types';

export async function getAllActiveResOfHotel(hotelId: number): Promise<IReservationsData> {
Expand Down Expand Up @@ -42,8 +43,8 @@ export async function getAllActiveResOfHotel(hotelId: number): Promise<IReservat

export async function getAllResByRange(
hotelId: number,
fromDate: Date,
toDate: Date
fromDate: string,
toDate: string
): Promise<IReservationsData> {
try {
const formatFromDate = new Date(fromDate).toISOString().split('T')[0]; //YYYY-MM-DD
Expand Down Expand Up @@ -72,7 +73,10 @@ export async function getAllResByRange(
}
}

export async function getAllResByDate(hotelId: number, resDate: Date): Promise<IReservationsData> {
export async function getAllResByDate(
hotelId: number,
resDate: string
): Promise<IReservationsData> {
try {
const formatResDate = new Date(resDate).toISOString().split('T')[0]; //YYYY-MM-DD
const reservationsData: Array<IReservations> = await Reservations.find({
Expand Down Expand Up @@ -104,19 +108,37 @@ export async function doRateShoping(
rateShopInfo: IRateShopPayload
): Promise<IRateShopResponse> {
try {
// First the check the availability of the Room for given date range again:
// First check the availability of the Room for given date range again:
const fromDate = new Date(rateShopInfo.checkIn).toISOString().split('T')[0]; //YYYY-MM-DD
const toDate = new Date(rateShopInfo.checkOut).toISOString().split('T')[0]; //YYYY-MM-DD
let maxNumOfPersonInRoom = 0;
let maxNumOfMattressInRoom = 0;
for (let index = 0; index < rateShopInfo.roomIds.length; index++) {
const roomAvailbility = await availabilityController.getAvailbilityByRoom(
hotelId,
rateShopInfo.roomIds[index],
fromDate,
toDate
);
const roomAvailbility: IAvailabilityData =
await availabilityController.getAvailbilityByRoom(
hotelId,
rateShopInfo.roomIds[index],
fromDate,
toDate
);
if (roomAvailbility.status !== 200) {
logger.error(
`Error while creating rate shop, room id ${rateShopInfo.roomIds[index]} is not available from range ${fromDate} - ${toDate}`
`Error while rate shop, room id ${rateShopInfo.roomIds[index]} is not available from range ${fromDate} - ${toDate}`
);
return {
status: 500
};
}
maxNumOfPersonInRoom +=
roomAvailbility.availabilityData?.[0].roomsInfo[0].numPerson ?? 0;
maxNumOfMattressInRoom +=
roomAvailbility.availabilityData?.[0].roomsInfo[0].maxMattress ?? 0;
if (
maxNumOfPersonInRoom < rateShopInfo.numOfPersons ||
maxNumOfMattressInRoom < rateShopInfo.numOfextraMattress
) {
logger.error(
`Error while rate shop, number of person ${rateShopInfo.numOfPersons} or number of mattress ${rateShopInfo.numOfextraMattress} is increasing room(s) capacity persons ${maxNumOfPersonInRoom}, extra mattress ${maxNumOfMattressInRoom}`
);
return {
status: 500
Expand All @@ -127,8 +149,9 @@ export async function doRateShoping(
const rateShopResponse: IRateShopSchema = {
hotelId: hotelId,
roomIds: [...rateShopInfo.roomIds],
checkIn: new Date(rateShopInfo.checkIn),
checkOut: new Date(rateShopInfo.checkOut),
checkIn: new Date(rateShopInfo.checkIn).toISOString().split('T')[0],
checkOut: new Date(rateShopInfo.checkOut).toISOString().split('T')[0],
totalNumDays: 0,
couponCode: rateShopInfo.couponCode ?? undefined,
voucherCode: rateShopInfo.voucherCode ?? undefined,
numOfPersons: rateShopInfo.numOfPersons,
Expand All @@ -140,7 +163,7 @@ export async function doRateShoping(
extraMattress: 0
},
chargesDetails: {
totalNumDays: 0,
totalDaysCharge: 0,
earlyCheckIn: undefined,
waiveEarlyCheckInRates: undefined,
waiveLateCheckOutRates: undefined,
Expand Down Expand Up @@ -169,17 +192,23 @@ export async function doRateShoping(
// Lets calulate number of days
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(
Math.abs((+rateShopResponse.checkOut - +rateShopResponse.checkIn) / oneDay)
Math.abs(
(+new Date(rateShopResponse.checkOut) - +new Date(rateShopResponse.checkIn)) /
oneDay
)
);
if (diffDays <= 0) {
logger.error(
`Error while creating rate shop, date diff is ${diffDays} from range ${fromDate} - ${toDate}`
`Error while rate shop, date diff is ${diffDays} from range ${fromDate} - ${toDate}`
);
return {
status: 500
};
}
rateShopResponse.chargesDetails.totalNumDays = diffDays;
logger.info(`Total days difference: ${diffDays}`);
rateShopResponse.totalNumDays = diffDays;
rateShopResponse.chargesDetails.totalDaysCharge =
diffDays * rateShopResponse.rates.perDayCharge;
rateShopResponse.chargesDetails.extraMattress =
rateShopResponse.rates.extraMattress * rateShopInfo.numOfextraMattress;
// check voucher
Expand Down Expand Up @@ -224,7 +253,10 @@ export async function createRes(hotelId: number, resInfo: IReservationsPayload)
try {
const rateShopResponse: IRateShopResponse = await doRateShoping(hotelId, resInfo);
if (rateShopResponse.status !== 200) {
throw new Error('Error doing rate shopping');
logger.error('Error doing rate shopping');
return {
status: 500
};
}
const reservationSchema: IReservationSchema = {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand All @@ -241,19 +273,21 @@ export async function createRes(hotelId: number, resInfo: IReservationsPayload)
session.startTransaction();
// create the guest profile and do the reservation
const createGuestData = await Guests.create(
{
hotelId: hotelId,
firstName: resInfo.firstName,
lastName: resInfo.lastName,
email: resInfo.email,
phoneNum: resInfo.phoneNum,
identityNum: resInfo.identityNum
},
[
{
hotelId: hotelId,
firstName: resInfo.firstName,
lastName: resInfo.lastName,
email: resInfo.email,
phoneNum: resInfo.phoneNum,
identityNum: resInfo.identityNum
}
],
{ session }
);
logger.info(`createGuestData ${JSON.stringify(createGuestData)}`);
reservationSchema.guestId = '123'; //For NOW
if (resInfo.paymentDetails.advancePayment >= 0) {
reservationSchema.guestId = createGuestData[0]._id; //For NOW
if (resInfo.paymentDetails.advancePayment > 0) {
reservationSchema.paymentDetails.advancePayment = resInfo.paymentDetails.advancePayment;
reservationSchema.paymentDetails.advancePaymentMode =
resInfo.paymentDetails.advancePaymentMode;
Expand All @@ -277,7 +311,7 @@ export async function createRes(hotelId: number, resInfo: IReservationsPayload)
restoDate: toDate,
resfromDate: fromDate,
resType: reservationSchema.confirmationType,
reservationId: '12345'
reservationId: createReservationRes[0]._id
}
}
},
Expand Down
5 changes: 5 additions & 0 deletions src/models/availability.models.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Document, Model, model, Schema } from 'mongoose';
import { IRoom } from './rooms.model';

export interface IAvailability extends Document {
hotelId: number;
Expand All @@ -11,6 +12,10 @@ export interface IAvailability extends Document {
}[];
}

export interface IAvailabilityWithRooms extends IAvailability {
roomsInfo: IRoom[];
}

const availabilitySchema: Schema = new Schema(
{
hotelId: Number,
Expand Down
8 changes: 5 additions & 3 deletions src/models/bookings.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface IBookings extends Document {
confirmationType: string;
checkIn: Date;
checkOut: Date;
totalNumDays: number;
guestId: string;
createdBy: string;
couponCode?: string;
Expand All @@ -19,7 +20,7 @@ export interface IBookings extends Document {
};
numOfPersons: number;
chargesDetails: {
totalNumDays: number;
totalDaysCharge: number;
earlyCheckIn?: number;
waiveEarlyCheckInRates?: boolean;
waiveLateCheckOutRates?: boolean;
Expand Down Expand Up @@ -72,7 +73,7 @@ const paymentDetailsSchema: Schema = new Schema({
});

const chargesSchema: Schema = new Schema({
totalNumDays: { type: Number, required: true },
totalDaysCharge: { type: Number, required: true },
earlyCheckIn: { type: Number, required: false },
waiveEarlyCheckInRates: { type: Boolean, required: false },
waiveLateCheckOutRates: { type: Boolean, required: false },
Expand All @@ -90,8 +91,9 @@ const bookingsSchema: Schema = new Schema(
confirmationType: { type: String, required: true },
checkIn: { type: Date, required: true },
checkOut: { type: Date, required: true },
totalNumDays: { type: Number, required: true },
guestId: { type: String, required: true },
createdBy: { type: String, required: true },
createdBy: { type: String, required: true, default: 'Uday' },
couponCode: { type: String, required: false },
voucherCode: { type: String, required: false },
rates: {
Expand Down
8 changes: 5 additions & 3 deletions src/models/reservations.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface IReservations extends Document {
confirmationType: string;
checkIn: Date;
checkOut: Date;
totalNumDays: number;
guestId: string;
createdBy?: string;
couponCode?: string;
Expand All @@ -20,7 +21,7 @@ export interface IReservations extends Document {
};
numOfPersons: number;
chargesDetails: {
totalNumDays: number;
totalDaysCharge: number;
earlyCheckIn?: number;
waiveEarlyCheckInRates?: boolean;
waiveLateCheckOutRates?: boolean;
Expand Down Expand Up @@ -60,7 +61,7 @@ const paymentDetailsSchema: Schema = new Schema({
});

const chargesSchema: Schema = new Schema({
totalNumDays: { type: Number, required: true },
totalDaysCharge: { type: Number, required: true },
earlyCheckIn: { type: Number, required: false },
waiveEarlyCheckInRates: { type: Boolean, required: false },
waiveLateCheckOutRates: { type: Boolean, required: false },
Expand All @@ -82,8 +83,9 @@ const reservationsSchema: Schema = new Schema(
},
checkIn: { type: Date, required: true },
checkOut: { type: Date, required: true },
totalNumDays: { type: Number, required: true },
guestId: { type: String, required: true },
createdBy: { type: String, required: true },
createdBy: { type: String, required: true, default: 'Uday' },
numOfextraMattress: { type: Number, required: true },
couponCode: { type: String, required: false, default: 'NA' },
voucherCode: { type: String, required: false, default: 'NA' },
Expand Down
File renamed without changes.
Loading

0 comments on commit 72cec7d

Please sign in to comment.