Skip to content

Commit

Permalink
chore(modify-notifications): Modify notifications table structure
Browse files Browse the repository at this point in the history
- create migration file to remove requestId column and add entity, entityId columns

- make notifications URL dynamic

[Finishes #170461063]
  • Loading branch information
nignanthomas committed Dec 28, 2019
1 parent c359928 commit b366bfd
Show file tree
Hide file tree
Showing 19 changed files with 109 additions and 187 deletions.
8 changes: 5 additions & 3 deletions src/controllers/accommodationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export default class AccommodationController {

static bookAccommdation(req, res) {
const {
checkInDate, checkOutDate, accomodationId, roomsNumber
checkInDate, checkOutDate, accomodationId, roomsNumber, host
} = req.body;

const APP_URL_BACKEND = `${req.protocol}://${req.headers.host}`;
Expand Down Expand Up @@ -172,7 +172,8 @@ export default class AccommodationController {
accommodation[0].owner,
APP_URL_BACKEND,
'placed',
'booking'
'booking',
host
);

return responseUtil(res, 200, strings.accommodation.success.SUCCESSFUL_BOOKED);
Expand Down Expand Up @@ -257,6 +258,7 @@ export default class AccommodationController {
const {
statusId, activity, subject, responseMessage, actionIsApprove
} = req;
const { host } = req.body;

const bookingToProcess = await bookingHelper.findOneBooking({ id });
const { accommodationId } = bookingToProcess;
Expand All @@ -280,7 +282,7 @@ export default class AccommodationController {
await bookingHelper.updateAccomodation(req, remainingSpace);
}

await notifSender(subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking');
await notifSender(subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.accommodations.error.BOOKING_NOT_FOUND, null, 404);
Expand Down
3 changes: 2 additions & 1 deletion src/controllers/commentsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export default class CommentsController {
const newComment = { comment, userId: id, requestId };
const addedComment = await models.comments.create(newComment);
const notification = await notifBuilder(
request,
'request',
request.id,
userNotiified,
`A comment has been made on request ${requestId}. Click here to view: ${APP_URL_BACKEND}/api/v1/requests/${requestId}.`,
);
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/destinationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import arrayMapper from '../helpers/arrayMapper';

export default class destinationController {
static async storeDestination(req, res, body, user, request) {
const { destinations } = body;
const { destinations, host } = body;
const APP_URL_BACKEND = `${req.protocol}://${req.headers.host}`;

await Promise.all(destinations.map(async destination => {
Expand All @@ -24,7 +24,7 @@ export default class destinationController {

const { lineManager } = user.payload;

await notifSender('Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request');
await notifSender('Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request', host);

return Utilities.responseHelper(
res,
Expand Down
5 changes: 1 addition & 4 deletions src/controllers/notificationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,16 @@
import strings from '../utils/stringsUtil';
import responseUtil from '../utils/responseUtil';
import notifServices from '../services/notifServices';
import bookingNotifServices from '../services/bookingNotifServices';
import { userNotidicationQuery } from '../utils/db/queries/notificationQueries';

const { allNotif, oneNotif, updateNotif } = notifServices;
const { bookingAllNotif } = bookingNotifServices;
const { NOTIF_NOT_FOUND, NOTIF_FOUND } = strings.notifications;

export default class notificationController {

static async allNotifications(req, res) {
const notifications = await allNotif(userNotidicationQuery(req.user.payload.id));
const bookingNotifications = await bookingAllNotif(req.user.payload.id);
const allNotifs = notifications.reverse().concat(bookingNotifications.reverse());
const allNotifs = notifications.reverse();
if (!allNotifs.length) {
return responseUtil(res, 404, NOTIF_NOT_FOUND);
}
Expand Down
5 changes: 3 additions & 2 deletions src/controllers/requestController.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export default class requestController {
const {
statusId, activity, subject, responseMessage
} = req;
const { host } = req.body;

const requestToProcess = await findOneRequest({ id });
const { userId } = requestToProcess;
Expand All @@ -94,7 +95,7 @@ export default class requestController {

request = request[1][0].dataValues;

await notifSender(subject, request, request.userId, APP_URL_BACKEND, activity, 'request');
await notifSender(subject, request, request.userId, APP_URL_BACKEND, activity, 'request', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.requests.NOT_FOUND, null, 404);
Expand Down Expand Up @@ -122,7 +123,7 @@ export default class requestController {

const request = await allSearch({ id });
const requestData = request[0].dataValues;
await notifSender('Request edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
await notifSender('Request Edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
return responseUtil(res, 200, strings.request.success.SUCCESS_UPDATE_REQUEST, request);
} catch (error) {
return res.status(500).json({ error: 'Something wrong' });
Expand Down

This file was deleted.

4 changes: 0 additions & 4 deletions src/database/migrations/20191113182004-addTimeNotification.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@ module.exports = {
queryInterface.addColumn('notifications', 'timestamp', {
type: Sequelize.TIME,
}, { transaction: t }),
queryInterface.addColumn('bookingNotifications', 'timestamp', {
type: Sequelize.TIME,
}, { transaction: t }),
])),

down: queryInterface => queryInterface.sequelize.transaction(t => Promise.all([
queryInterface.removeColumn('notifications', 'timestamp', { transaction: t }),
queryInterface.removeColumn('bookingNotifications', 'timestamp', { transaction: t }),
])),
};
23 changes: 23 additions & 0 deletions src/database/migrations/20191227205540-entity-entityId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.sequelize.transaction(t => Promise.all([
queryInterface.addColumn('notifications', 'entity', {
type: Sequelize.STRING,
allowNull: true
}, { transaction: t }),
queryInterface.addColumn('notifications', 'entityId', {
type: Sequelize.INTEGER,
allowNull: true
}, { transaction: t }),
queryInterface.removeColumn('notifications', 'requestId', { transaction: t }),

])),

down: (queryInterface, Sequelize) => queryInterface.sequelize.transaction(t => Promise.all([
queryInterface.addColumn('notifications', 'requestId', {
type: Sequelize.INTEGER,
allowNull: true
}, { transaction: t }),
queryInterface.removeColumn('notifications', 'entity', { transaction: t }),
queryInterface.removeColumn('notifications', 'entityId', { transaction: t }),
])),
};
30 changes: 0 additions & 30 deletions src/database/models/bookingnotifications.js

This file was deleted.

11 changes: 6 additions & 5 deletions src/database/models/notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const notifications = sequelize.define('notifications', {
requestId: DataTypes.INTEGER,
entityId: DataTypes.INTEGER,
entity: DataTypes.STRING,
userNotified: DataTypes.INTEGER,
activity: DataTypes.STRING,
timestamp: {
Expand All @@ -17,10 +18,10 @@ module.exports = (sequelize, DataTypes) => {
});
notifications.associate = function(models) {
// associations can be defined here
notifications.belongsTo(models.requests, {
as: 'request',
foreignKey: 'requestId',
});
// notifications.belongsTo(models.requests, {
// as: 'request',
// foreignKey: 'requestId',
// });
notifications.belongsTo(models.users, {
as: 'notifiedUser',
foreignKey: 'userNotified'
Expand Down
15 changes: 10 additions & 5 deletions src/database/seeders/20191028170529-notificationsTableSeeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ module.exports = {
up: (queryInterface, Sequelize) => Promise.all([
queryInterface.bulkInsert('notifications', [
{
requestId: 2,
entity: 'request',
entityId: 2,
userNotified: 8,
activity: 'A request has been created. Click here to view: https://caret-bn-backend-staging.herokuapp.com/api/v1/requests/2.',
isRead: false,
Expand All @@ -13,7 +14,8 @@ module.exports = {
timestamp: new Date()
},
{
requestId: 2,
entity: 'request',
entityId: 2,
userNotified: 3,
activity: 'A request has been rejected. Click here to view: https://caret-bn-backend-staging.herokuapp.com/api/v1/requests/2.',
isRead: true,
Expand All @@ -22,7 +24,8 @@ module.exports = {
timestamp: new Date()
},
{
requestId: 2,
entity: 'request',
entityId: 2,
userNotified: 3,
activity: 'A request has been approved. Click here to view: https://caret-bn-backend-staging.herokuapp.com/api/v1/requests/2.',
isRead: false,
Expand All @@ -31,7 +34,8 @@ module.exports = {
timestamp: new Date()
},
{
requestId: 2,
entity: 'request',
entityId: 2,
userNotified: 3,
activity: 'A request has been approved. Click here to view: https://caret-bn-backend-staging.herokuapp.com/api/v1/requests/2.',
isRead: false,
Expand All @@ -40,7 +44,8 @@ module.exports = {
timestamp: new Date()
},
{
requestId: 2,
entity: 'request',
entityId: 2,
userNotified: 3,
activity: 'A request has been approved. Click here to view: https://caret-bn-backend-staging.herokuapp.com/api/v1/requests/2.',
isRead: false,
Expand Down
22 changes: 8 additions & 14 deletions src/helpers/notifSender.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
import findUser from './findUser';
import notifServices from '../services/notifServices';
import bookingNotifServices from '../services/bookingNotifServices';

dotenv.config();

const { EMAIL_PASSWORD, EMAIL_ADDRESS } = process.env;
const { notifSaver, notifBuilder } = notifServices;
const { bookingNotifSaver, bookingNotifBuilder } = bookingNotifServices;

const transporter = nodemailer.createTransport({
service: 'gmail',
Expand All @@ -18,22 +16,18 @@ const transporter = nodemailer.createTransport({
}
});

const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, table) => {
const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, table, host) => {
try {
const user = await findUser({ id: userId });
const activityMessage = `A ${table} has been ${activity}. Click here to view: ${APP_URL_BACKEND}/api/v1/${table}s/${object.id}.`;
const URL = host ? `${host}/${table}s/${object.id}` : `${APP_URL_BACKEND}/api/v1/${table}s/${object.id}`;
const activityMessage = `A ${table} has been ${activity}. Click here to view: ${URL}.`;

if (user.appNotif) {
let notification;
switch (table) {
case 'request':
notification = await notifBuilder(object, userId, activityMessage);
const notification = await notifBuilder(table, object.id, userId, activityMessage);
try {
await notifSaver(notification);
break;
case 'booking':
notification = await bookingNotifBuilder(object, userId, activityMessage);
await bookingNotifSaver(notification);
break;
} catch (error) {
return error;
}
}

Expand All @@ -48,7 +42,7 @@ const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, t
<p style="font-family:Avenir,Helvetica,sans-serif;box-sizing:border-box;color:#74787e;font-size:16px;line-height:1.5em;margin-top:0;text-align:left">
Hello dear ${username}, <br> This is to notify you that a ${table} has been ${activity}. <br> Click the button below to view the ${table}.
</p>
<p><a style="background-color: #3097d1; border: 2px solid #3097d1; padding: 8px; color: #fff; font-size: 16px; text-decoration: none;cursor: pointer;" href="${APP_URL_BACKEND}/api/v1/${table}s/${object.id}">View ${table}</a></a></p>
<p><a style="background-color: #3097d1; border: 2px solid #3097d1; padding: 8px; color: #fff; font-size: 16px; text-decoration: none;cursor: pointer;" href="${URL}">View ${table}</a></a></p>
<p style="color:#74787e;font-size:16px;line-height:1.5em;margin-top:0;text-align:left">Thank you for using our system!</p>
<p style="color:#74787e;font-size:16px;line-height:1.5em;margin-top:0;">Regards,<br>Barefoot Nomad Caret Team</p>
</div>`
Expand Down
1 change: 1 addition & 0 deletions src/middlewares/inputValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export default class InputValidation {
checkOutDate: Joi.string().regex(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/).message('checkOutDate format must be YYYY-MM-DD').required(),
accomodationId: Joi.number().integer().min(1).required(),
roomsNumber: Joi.number().integer().min(1).required(),
host: Joi.string().uri().trim().message('host must be a valid URL'),
});
validation(req, res, schema, next);
}
Expand Down
36 changes: 0 additions & 36 deletions src/services/bookingNotifServices.js

This file was deleted.

Loading

0 comments on commit b366bfd

Please sign in to comment.