Skip to content

Commit

Permalink
bg(ensure that the email is sent to the line manager): added email no…
Browse files Browse the repository at this point in the history
…tification functionality

added fetch single trip route
[#Starts #170258130]
  • Loading branch information
hezzie committed Dec 16, 2019
1 parent 1edface commit 31e2a7c
Show file tree
Hide file tree
Showing 31 changed files with 522 additions and 130 deletions.
19 changes: 18 additions & 1 deletion src/controllers/AccommodationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import dotenv from 'dotenv';
import Response from '../helpers/Response';
import AccommodationService from '../services/AccommodationService';

const { createNewRating, createAccomodation } = AccommodationService;
const { createNewRating, createAccomodation, getAccommodations } = AccommodationService;
dotenv.config();
/**
* @exports
Expand Down Expand Up @@ -71,6 +71,23 @@ class AccommodationController {
return Response.errorMessage(req, res, 'Server Error', 500);
}
}

/**
* Travel Admin can be able to create accommodation facility
* @static
* @param {object} req request object
* @param {object} res response object
* @memberof AccommodationController
* @returns {object} data
*/
static async getAccommodations(req, res) {
try {
const accommodations = await getAccommodations(req);
return Response.successMessage(req, res, 'Accommodation/s successfully fetched', accommodations, 200);
} catch (err) {
return Response.errorMessage(req, res, 'Server Error', 500);
}
}
}

export default AccommodationController;
2 changes: 1 addition & 1 deletion src/controllers/CommentController.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class CommentController {
static async getComments(req, res) {
try {
const tripComments = await CommentService.getComments(req);
return tripComments ? Response.successMessage(req, res, 'All comments about this trip request have been retrieved successfuly!', tripComments, 200)
return tripComments[0] ? Response.successMessage(req, res, 'All comments about this trip request have been retrieved successfuly!', tripComments, 200)
: Response.errorMessage(req, res, 'No comments for this trip yet!', 200);
} catch (error) {
return Response.errorMessage(req, res, 'Server error', 500);
Expand Down
18 changes: 18 additions & 0 deletions src/controllers/TripController.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,24 @@ class TripController {
}
}

/**
* fetch a single trip
* @static
* @param {object} req request object
* @param {object} res response object
* @memberof TripController
* @returns {object} data
*/
static async getSingleTrip(req, res) {
try {
const { tripId } = req.params;
const result = await TripService.getSingleTrip(tripId);
return Response.successMessage(req, res, 'succesfully fetched one trip', result, 200);
} catch (err) {
return Response.errorMessage(req, res, err.message, 500);
}
}

/**
* Manager should be able to accept a trip request
* @static
Expand Down
1 change: 0 additions & 1 deletion src/database/models/booking.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module.exports = (sequelize, DataTypes) => {
const booking = sequelize.define('booking', {
tripId: DataTypes.INTEGER,
roomId: DataTypes.INTEGER,
userId: DataTypes.INTEGER,
checkInDate: DataTypes.DATE,
checkOutDate: DataTypes.DATE
}, {});
Expand Down
5 changes: 2 additions & 3 deletions src/helpers/EmailHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ class EmailHelper {
* rsend email to the manager
* @static
* @param {Object} req the template to use
* @param {Object} email the template to use
* @returns {Object} sendEmail
*/
static approveEmailHelper(req, email) {
transporter.sendMail(EmailTemplates.approveEmailTemplate(req, email));
static approveEmailHelper(req) {
transporter.sendMail(EmailTemplates.approveEmailTemplate(req));
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/helpers/EmailTemplates.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import dotenv from 'dotenv';
import AuthenticateToken from './AuthenticateToken';

dotenv.config();
const { EMAIL_ADDRESS, MANAGER } = process.env;
const { EMAIL_ADDRESS } = process.env;

/**
* @export
Expand Down Expand Up @@ -129,12 +129,12 @@ class EmailTemplates {
* @param {Object} email the template to use
* @returns {Object} sendEmail
*/
static approveEmailTemplate(req, email) {
static approveEmailTemplate(req) {
return {
to: email,
to: req.user.managerInfo.email,
from: EMAIL_ADDRESS,
subject: 'Trip request',
html: `<h4>Hi, ${MANAGER},</h4>
html: `<h4>Hi, ${req.user.managerInfo.firstName},</h4>
<p>${req.user.firstName} has made a multi trip request, the reason for the request is ${req.body.reason}</p>`
};
}
Expand Down
30 changes: 24 additions & 6 deletions src/helpers/TripHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import Response from './Response';
import emailHelper from './EmailHelper';
import CommonQueries from '../services/CommonQueries';
import { tripRequests, trips, cities } from '../database/models';
import {
tripRequests, trips, cities, userProfile, users, accommodations
} from '../database/models';
import NotificationService from '../services/NotificationService';


Expand Down Expand Up @@ -40,10 +42,16 @@ class TripHelper {
returnDate: item.returnDate
});
});

req.result = newTrip;
await NotificationService.newTripRequestNotification(req);
emailHelper.approveEmailHelper(req, process.env.MANAGER_EMAIL);
const { id } = req.user;
const userInfo = await CommonQueries.findOne(userProfile,
{ where: { userId: id }, raw: true });
const { managerId } = userInfo;
const managerInfo = await CommonQueries.findOne(users,
{ where: { id: managerId }, raw: true });
req.user.managerInfo = managerInfo;
emailHelper.approveEmailHelper(req);
return Response.successMessage(req, res, 'Trip requested successfully', newTrip, 201);
} catch (err) {
return Response.errorMessage(req, res, err.message, 500);
Expand All @@ -58,8 +66,16 @@ class TripHelper {
* @returns {object} data
*/
static async getCityName(tripTypeId) {
const { dataValues: origin } = await CommonQueries.findOne(cities, { where: { id: tripTypeId.originId }, attributes: ['city'] });
const { dataValues: destination } = await CommonQueries.findOne(cities, { where: { id: tripTypeId.destinationId }, attributes: ['city'] });
const { dataValues: origin } = await CommonQueries.findOne(cities,
{
where: { id: tripTypeId.originId },
attributes: ['city']
});
const { dataValues: destination } = await CommonQueries.findOne(cities,
{
where: { id: tripTypeId.destinationId },
attributes: ['city']
});
return { origin, destination };
}

Expand All @@ -84,7 +100,9 @@ class TripHelper {
if (getDestinationIds[z] === getDestinationIds[i]) count++;
}
countHolder.push(count);
newArray.push({ counter: count, cityId: getDestinationIds[i] });
newArray.push({
counter: count, cityId: getDestinationIds[i], city: null, accommodationNo: null
});
}
const maxNumber = Math.max(...countHolder);
const frequentCityId = newArray.filter((item) => {
Expand Down
6 changes: 4 additions & 2 deletions src/middlewares/AccommodationMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class AccommodationMiddleware {
isAccommodationExist, allAvailRoom, isRoomBooked
} = serviceQueries;

const isOwnerOfTheTrip = await BookingService.isOwnerOftheTripService(req);
const isOwnerOfTheTrip = await BookingService.isOwnerOftheTripService(req, res);

if (isOwnerOfTheTrip.length === 0) {
return Response.errorMessage(req, res, 'Sorry, You are not the owner of this trip request', 403);
Expand All @@ -53,7 +53,9 @@ class AccommodationMiddleware {
}
let isBookable;
isRoomBooked.forEach(x => {
if (new Date(x.checkOutDate) > new Date(checkInDate)) { isBookable = true; }
if (
new Date(x.checkOutDate) > new Date(checkInDate)
&& x.id === roomId) { isBookable = true; }
});

if (isBookable) {
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/Conflict.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Conflict {
* @returns {object} data
*/
static isUsersConflict(req, res, next) {
return DataEngine.findOne(req, res, next, users, { id: req.params.id }, 'The user already exist');
return DataEngine.findOne(req, res, next, users, { email: req.body.email }, `${req.body.email} does not exist`);
}

/**
Expand Down Expand Up @@ -87,7 +87,7 @@ class Conflict {
);
}

/**
/**
* Check if accomodation already exist
* @static
* @param {object} req request object
Expand Down
33 changes: 33 additions & 0 deletions src/middlewares/Validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,39 @@ class Validate {
];
}

/**
* Validate input
* @static
* @returns {object} errors
*/
static isTripIDInteger() {
return [
check('tripId', 'ID should be an integer').isInt(),
];
}

/**
* Validate input
* @static
* @returns {object} errors
*/
static isAccommodationIDInteger() {
return [
check('accommodationId', 'ID should be an integer').isInt(),
];
}

/**
* Validate input
* @static
* @returns {object} errors
*/
static validateResendEmail() {
return [
check('email', 'email should be valid').trim().isEmail(),
];
}

/**
* Validate accommodation params
* @static
Expand Down
1 change: 0 additions & 1 deletion src/middlewares/ValidateAccommodation.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export default class ValidateAccommodation {
*/
static async checkIfCheckInDateIsAsCheckOutDate(req, res, next) {
const { checkInDate, checkOutDate } = req.body;

const checkInDateCheckOutDate = {};
const checkInDates = new Date(checkInDate);
const checkOutDates = new Date(checkOutDate);
Expand Down
34 changes: 33 additions & 1 deletion src/middlewares/findUsers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Response from '../helpers/Response';
import {
users, tripRequests, userProfile, comments
users, tripRequests, userProfile, comments, trips
} from '../database/models';
import CommonQueries from '../services/CommonQueries';

Expand Down Expand Up @@ -53,6 +53,38 @@ export const commentAccess = async (req, res, next) => {
}
return Response.errorMessage(req, res, 'You should be either a requester or a manager', 403);
};
export const tripAccess = async (req, res, next) => {
const { id } = req.user;
const { tripId } = req.params;
const userObj = {
where: { id: tripId },
include: [{
model: tripRequests,
}],
};
const tripObj = {
where: {
id: tripId,
},
include: [{
model: tripRequests,
where: { userId: id, }
}]
};
const tripUser = await CommonQueries.findOne(trips, userObj);
const userId = tripUser.dataValues.tripRequest.dataValues.userId;
const qObject = {
where:{userId, managerId:id}
}
const isManager = await CommonQueries.findOne(userProfile, qObject);

const isRequester = await CommonQueries.findOne(trips, tripObj);

if (isManager || isRequester) {
return next();
}
return Response.errorMessage(req, res, 'You should be either a requester or a manager', 403);
};
export const isManagerHasAccess = async (req, res, next) => {
const getRole = await users.findAll({ where: { roleId: req.user.roleId }, raw: true });
const [{ roleId }] = getRole;
Expand Down
2 changes: 0 additions & 2 deletions src/middlewares/verifyToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import Response from '../helpers/Response';
* next
*/
const verifyToken = (req, res, next) => {


const token = !req.headers.token ? req.params.token : req.headers.token;
if (!token) {
return Response.errorMessage(req, res, 'Please, insert the token', 401);
Expand Down
5 changes: 3 additions & 2 deletions src/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost:3000');
const socket = io('https://team-odd-bn-backend-staging.herokuapp.com/');
socket.on('approve_reject_client', (name) => {
console.log(JSON.parse(name));
});
Expand All @@ -29,6 +29,7 @@
socket.on('trip_request_client', (name) => {
console.log(JSON.parse(name));
});

</script>

</html>
Loading

0 comments on commit 31e2a7c

Please sign in to comment.