-
Notifications
You must be signed in to change notification settings - Fork 0
/
railRoutes.js
230 lines (202 loc) · 6.89 KB
/
railRoutes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import * as mongoose from 'mongoose';
import RailRoute from '../models/railRoute.js';
import Reservation from '../models/reservation.js';
import Train from '../models/train.js';
// Helper function
const joinByIds = name => ({
$lookup: {
from: 'stops',
localField: `${name}.stopId`,
foreignField: '_id',
as: `${name}.stop`,
pipeline: [
{
$lookup: {
from: 'places',
localField: 'placeId',
foreignField: '_id',
as: 'places',
pipeline: [
{
$unset: [ '__v' ]
}
]
}
},
{
$project: {
'_id': true,
'name': true,
'place': { $first: '$places' }
}
}
]
}
});
const insertRailRoute = async (req, res) => {
const body = req.body;
const newRailRoute = await RailRoute.create({
trainId: new mongoose.Types.ObjectId(body.trainId),
ticketsCost: {
'firstClass': body.ticketsCost.firstClass,
'standard': body.ticketsCost.standard
},
departure: {
stopId: new mongoose.Types.ObjectId(body.departure.stopId),
date: new Date(body.departure.date)
},
arrival: {
stopId: new mongoose.Types.ObjectId(body.arrival.stopId),
date: new Date(body.arrival.date)
},
stops: body.stops
});
console.log(newRailRoute);
res.json({ railRouteId: newRailRoute._id });
};
const getRailRouteById = async (req, res) => {
const railRouteId = req.params.id;
if (typeof railRouteId !== 'string') {
res.status(400);
throw new Error(`Rail route ID ${railRouteId} is not string type`);
}
if (railRouteId.length !== 24) {
res.status(400);
const lengthMessage = railRouteId.length < 24 ? 'short' : 'long';
throw new Error(`Rail route ID is too ${lengthMessage} (24 characters)`);
}
const railRoute = await RailRoute.findById(railRouteId);
if (!railRoute) {
res.status(404);
throw new Error(`Rail route ${railRouteId} not found`);
}
res.json(railRoute);
};
const getRailRouteQuery = async (req, res) => {
const departureDateString = req.body.departureDate,
arrivalDateString = req.body.arrivalDate,
departureStopId = req.body.departureStopId,
arrivalStopId = req.body.arrivalStopId;
console.log(req.body);
if (typeof departureDateString === 'undefined' && typeof arrivalDateString === 'undefined') {
res.status(400);
throw new Error('Departure and arrival dates are both undefined (unsent)');
}
if (typeof departureStopId === 'undefined') {
res.status(400);
throw new Error('Departure stop ID is undefined (unsent)');
}
if (departureStopId.length !== 24) {
res.status(400);
const lengthMessage = departureStopId.length < 24 ? 'short' : 'long';
throw new Error(`Departure stop ID '${departureStopId}' is too ${lengthMessage} (24 characters)`);
}
if (typeof arrivalStopId === 'undefined') {
res.status(400);
throw new Error('Arrival stop ID is undefined (unsent)');
}
if (arrivalStopId.length !== 24) {
res.status(400);
const lengthMessage = arrivalStopId.length < 24 ? 'short' : 'long';
throw new Error(`Arrival stop ID '${arrivalStopId}' is too ${lengthMessage} (24 characters)`);
}
const departureDate = new Date(departureDateString),
arrivalDate = new Date(arrivalDateString);
// if (!isNaN(departureDate.valueOf())
// && !isNaN(arrivalDate.valueOf())
// && arrivalDate - departureDate <= 0
// ) {
// res.status(400);
// throw new Error('Arrival date is older than departure one');
// }
const matchStage = {};
if (!isNaN(departureDate.valueOf())) {
matchStage['departure.date'] = { $gte: departureDate };
}
else if (!isNaN(arrivalDate.valueOf())) {
matchStage['arrival.date'] = { $lte: arrivalDate };
}
const departureId = new mongoose.Types.ObjectId(departureStopId),
arrivalId = new mongoose.Types.ObjectId(arrivalStopId);
matchStage.$and = [
{
$or: [
{ 'departure.stopId': departureId },
{
'stops': {
$elemMatch: { 'stopId': departureId }
}
}
]
},
{
$or: [
{ 'arrival.stopId': arrivalId },
{
'stops': {
$elemMatch: { 'stopId': arrivalId }
}
}
]
}
];
const railRoutes = await RailRoute.aggregate([
{ $match: matchStage },
joinByIds('departure'),
joinByIds('arrival'),
joinByIds('stops'),
{ $unset: [ '__v' ] }
])
.exec();
if (railRoutes.length === 0) {
res.status(404);
throw new Error(`Rail routes not found`);
}
// console.log(railRoutes);
res.json(railRoutes);
};
const getVacantSeatsById = async (req, res) => {
const railRouteId = new mongoose.Types.ObjectId(req.params.id);
// Get the reserved seats by rail route ID
const reservedSeatsObject = await Reservation.aggregate([
{ $match: { railRouteId } },
{
$project: {
'_id': false,
'seats': { $concatArrays: '$seats' }
}
},
]);
const reservedSeats = reservedSeatsObject[0].seats;
const reservedSeatIds = reservedSeats.map(seat => seat.seatId);
console.log(reservedSeatIds);
// Get the train ID of the rail route
const railRoute = await RailRoute.findById(railRouteId);
const trainId = railRoute.trainId;
// Find the vacant seats by rail route ID
const vacantSeatsObject = await Train.aggregate([
{ $match: { '_id': trainId } },
{ $project: { 'seats': true } }
]);
// console.log(vacantSeatsObject);
const vacantSeatsMap = vacantSeatsObject[0].seats;
// console.log(vacantSeatsMap)
reservedSeatIds.forEach(id => delete vacantSeatsMap[id]);
// if (vacantSeatsMap === 0) {
// console.log(chalk.cyan.bold('[Get vacant seats by rail route ID]') + ` Vacant seats not found`);
// }
// console.log(chalk.cyan.bold('[Get vacant seats by rail route ID]') + ` Vacant seats found`);
res.json(vacantSeatsMap);
};
const getRailRouteByDeparture = async (req, res) => {
};
const getRailRouteByArrival = async (req, res) => {
};
export {
insertRailRoute,
getRailRouteById,
getRailRouteQuery,
getVacantSeatsById,
getRailRouteByDeparture,
getRailRouteByArrival
};