Skip to content

Commit

Permalink
feat(trip): user can create multi-city requests
Browse files Browse the repository at this point in the history
[Delivers #167891583]
  • Loading branch information
max-wel authored and meetKazuki committed Sep 9, 2019
1 parent 7562fb7 commit e9e2b8e
Show file tree
Hide file tree
Showing 7 changed files with 219 additions and 430 deletions.
72 changes: 8 additions & 64 deletions src/controllers/Trip.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,71 +46,15 @@ class TripController {
* @returns {object} JSON
*/
static async createTripRequest(req, res) {
try {
const { payload } = req.payload;
const { id: userId } = payload;
const {
type, from, departureDate, returnDate, destination, reason
} = req.body;
const { to, accomodation } = destination;

const trip = await Trip.create(
{
type,
userId,
startBranchId: from,
reason,
tripDate: departureDate,
returnDate: type === 'oneway' ? null : returnDate,
stop: {
destinationBranchId: to,
accomodationId: accomodation,
}
},
{
include: [
{
model: Stop,
as: 'stop'
}
]
}
);
const response = new Response(
true,
201,
'Travel request successfully created',
{ trip }
);
return res.status(response.code).json(response);
} catch (error) {
const response = new Response(
false,
500,
'Server error, Please try again later'
);
return res.status(response.code).json(response);
}
}

/**
*
* @param {object} req Request
* @param {object} res Response
* @returns {object} JSON
*/
static async createMultiCityRequest(req, res) {
try {
const { payload: { id: userId } } = req.payload;
const {
type, from, departureDate, reason, destination
type, from, departureDate, returnDate, destinations, reason
} = req.body;
// eslint-disable-next-line no-unused-vars
const { to, accomodation } = destination;

const stops = destination.map((data) => ({
destinationBranchId: data.to,
accomodationId: data.accomodation,
const stops = destinations.map(({ to, accomodation }) => ({
destinationBranchId: to,
accomodationId: accomodation,
}));

const trip = await Trip.create(
Expand All @@ -120,30 +64,30 @@ class TripController {
startBranchId: from,
reason,
tripDate: departureDate,
returnDate: type === 'return' ? returnDate : null,
stop: stops
},
{
include: [
{
model: Stop,
as: 'stop'
as: 'stop',
}
]
}
);

const response = new Response(
true,
201,
'MultiCity request created successfully',
'Travel request successfully created',
{ trip }
);
return res.status(response.code).json(response);
} catch (error) {
const response = new Response(
false,
500,
'Internal server error'
'Server error, Please try again later'
);
return res.status(response.code).json(response);
}
Expand Down
2 changes: 1 addition & 1 deletion src/database/seeders/20190821112700-users.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module.exports = {
firstName: 'Desmond',
lastName: 'Edem',
email: 'kukiito219@gmail.com',
password: '12345678',
password: hashHelper.hashPassword('12345678'),
gender: 'male',
dob: '2012-09-12',
status: 'active',
Expand Down
10 changes: 3 additions & 7 deletions src/routes/trip.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { Router } from 'express';
import TripController from '../controllers/Trip';
import Token from '../helpers/Token';
import validator from '../middlewares/validator';
import { tripRequestSchema, multiTripSchema } from '../validation/tripSchema';
import verify from '../middlewares/AuthMiddlewares';
import { tripRequestSchema } from '../validation/tripSchema';

const tripRoutes = Router();

Expand All @@ -11,14 +12,9 @@ tripRoutes.get('/user', Token.verifyToken, TripController.getUserTrips);
tripRoutes.post(
'/',
Token.verifyToken,
verify.isUserVerified,
validator(tripRequestSchema),
TripController.createTripRequest
);
tripRoutes.post(
'/multi',
Token.verifyToken,
validator(multiTripSchema),
TripController.createMultiCityRequest
);

export default tripRoutes;
77 changes: 18 additions & 59 deletions src/validation/tripSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const tripRequestSchema = [
.not().isEmpty({ ignore_whitespace: true })
.withMessage('Trip type is required')
.trim()
.isIn(['oneway', 'return'])
.isIn(['oneway', 'return', 'multiple'])
.withMessage('Invalid trip type'),
body('from')
.not().isEmpty({ ignore_whitespace: true })
Expand Down Expand Up @@ -49,24 +49,37 @@ const tripRequestSchema = [
.not().isEmpty({ ignore_whitespace: true })
.withMessage('Travel reason is required')
.trim(),
body('destination.to')
body('destinations')
.not().isEmpty()
.withMessage('Destination(s) is required')
.isArray()
.withMessage('Invalid destination format'),
body('destinations.*.to')
.exists()
.withMessage('Destination does not exist')
.trim()
.isUUID(4)
.withMessage('Invalid destination format')
.custom(async (value, { req }) => {
const { destinations } = req.body;
const branch = await Branch.findOne({ where: { id: value } });
if (!branch) {
throw new Error('Destination does not exist');
}
if (value === req.body.from) {
throw new Error('Start and Destination should not be the same');
}

const filtered = destinations.filter(
(data) => data.to === value
);
if (filtered.length > 1) {
throw new Error('One or more destination branches are the same');
}
return true;
}),
body('destination.accomodation')
.exists()
body('destinations.*.accomodation')
.not().isEmpty()
.withMessage('Accomodation does not exist')
.trim()
.isUUID(4)
Expand All @@ -80,58 +93,4 @@ const tripRequestSchema = [
}),
];

const multiTripSchema = [
body('type')
.exists()
.withMessage('Specify trip type')
.trim()
.equals('multiple')
.withMessage('Invalid option specified'),

body('from')
.not().isEmpty({ ignore_whitespace: true })
.withMessage('Starting point is required')
.trim()
.isUUID(4)
.withMessage('Invalid starting point')
.custom(async (value) => {
const branch = await Branch.findOne({ where: { id: value } });
if (!branch) {
throw new Error('Start branch location does not exist');
}
return true;
}),

body('destination.*.to')
.exists()
.withMessage('Destination is required')
.trim()
.isUUID(4)
.withMessage('Invalid destination format')
.custom(async (value, { req }) => {
const { destination } = req.body;
const branch = await Branch.findOne({ where: { id: value } });
if (!branch) {
throw new Error('Destination branch does not exist');
}
if (value === req.body.from) {
throw new Error('Start and Destination branch should not be the same');
}
const filtered = destination.filter(
(data) => data.to === value
);
if (filtered.length > 1) {
throw new Error('One or more destination branches are the same');
}
return true;
}),

body('departureDate')
.not().isEmpty({ ignore_whitespace: true })
.withMessage('Departure date is required')
.custom((value) => isValid(parseISO(value)))
.withMessage('Invalid departure date format')
.customSanitizer((value) => new Date(value)),
];

export { tripRequestSchema, multiTripSchema };
export { tripRequestSchema };
9 changes: 8 additions & 1 deletion test/mockData/mockAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,12 @@ const incorrectCompanyId = {
role: 'staff',
};

const unverifiedLogin = {
email: 'john.doe@gmail.com',
password: 'password2019',
code: '4RHJHJJKSK'
};

const users = {
user1,
user2,
Expand Down Expand Up @@ -362,7 +368,8 @@ const users = {
superAdminLogin,
unverifiedUser,
credentialsWithoutRole,
incorrectCompanyId
incorrectCompanyId,
unverifiedLogin
};

export default users;
Loading

0 comments on commit e9e2b8e

Please sign in to comment.