2023-05-31 20:04:00 +01:00
|
|
|
const log = require('../utils/log.utils');
|
|
|
|
const db = require('./dbAccess.services');
|
|
|
|
const clean = require('../utils/sanitizer.utils');
|
2023-06-01 00:10:14 +01:00
|
|
|
const pis = require('../services/pis.services');
|
2023-05-31 20:04:00 +01:00
|
|
|
|
2023-06-01 12:40:43 +01:00
|
|
|
async function findByHeadcodeToday(headcode) {
|
2023-05-31 20:04:00 +01:00
|
|
|
const sanitizedHeadcode = clean.removeNonAlphanumeric(headcode);
|
|
|
|
log.out(`trainServiceServices.findByHeadcode: Searching for headcode ${sanitizedHeadcode}`, 'dbug');
|
|
|
|
const now = new Date();
|
|
|
|
const dayMap = ['su', 'm', 't', 'w', 'th', 'f', 's'];
|
|
|
|
const shortDay = dayMap[now.getDay()]; // Fetch short day from map
|
|
|
|
const query = {
|
|
|
|
headcode: sanitizedHeadcode,
|
|
|
|
scheduleStartDate: {$lte: now},
|
|
|
|
scheduleEndDate: {$gte: now},
|
|
|
|
daysRun: {$in: [shortDay]}
|
|
|
|
};
|
2023-06-01 12:40:43 +01:00
|
|
|
const queryData = await db.query('timetable', query);
|
|
|
|
let trainData = queryData;
|
2023-05-31 20:40:34 +01:00
|
|
|
// At this point, the returned objects need sorting to ensure the correct object is returned.
|
|
|
|
// C, N, O, P is the order - C being the preferred, then N, then O and finally P.
|
2023-06-01 12:40:43 +01:00
|
|
|
let preparedData = [];
|
|
|
|
for (const trainService in trainData) {
|
|
|
|
// Search for PIS Code for each service
|
|
|
|
let tiplocList = await getPublicStops(trainData[trainService]['stops']);
|
|
|
|
const pisDetail = await pis.findByTiplocArray(tiplocList);
|
|
|
|
trainData[trainService]['pis'] = pisDetail?.[0]?.['code'] ?? 'None';
|
|
|
|
trainData[trainService]['publicStops'] = tiplocList;
|
|
|
|
preparedData.push(trainData[trainService]);
|
|
|
|
}
|
|
|
|
return preparedData;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getPublicStops(data) {
|
|
|
|
let tiplocList = [];
|
|
|
|
for (const publicStop in data) {
|
|
|
|
if (data[publicStop]['isPublic']) {
|
|
|
|
tiplocList.push(data[publicStop]['tiploc']);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return tiplocList;
|
2023-05-31 20:04:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2023-06-01 12:40:43 +01:00
|
|
|
findByHeadcodeToday,
|
2023-05-31 20:04:00 +01:00
|
|
|
};
|