timetable: findByHeadcode now only returns enough data to give user a list of services which can then be expanded by using findByTrainUid

Signed-off-by: Fred Boniface <fred@fjla.uk>
This commit is contained in:
Fred Boniface 2023-07-12 23:18:32 +01:00
parent 86e5c34e7f
commit 3818bc5d62
3 changed files with 86 additions and 40 deletions

View File

@ -30,6 +30,9 @@ async function get(req, res, next) {
case 'headcode': case 'headcode':
res.json(await train.findByHeadcode(date, id)); res.json(await train.findByHeadcode(date, id));
break; break;
case 'trainuid':
res.json(await train.findByTrainUid(id, date));
break;
default: default:
res.status(404).json({ res.status(404).json({
status:'error', status:'error',

View File

@ -26,6 +26,24 @@ async function query(collection, query, returnId = false){
return (await qcursor.toArray()); return (await qcursor.toArray());
} }
async function queryProject(collection, query, projection) {
await client.connect();
log.out(`dbAccess.queryProject: Connecting to col: '${collection}'`, 'info');
const qcoll = db.collection(collection);
const qcursor = qcoll.find(query).project(projection);
log.out(`dbAccess.query: Running Query: ${JSON.stringify(query)}, Projection: ${JSON.stringify(projection)}`, 'dbug');
increment(collection);
return await qcursor.toArray();
}
async function queryAggregate(collection, pipeline) {
await client.connect();
log.out(`dbAccess.queryProject: Connecting to col: '${collection}'`, 'info');
log.out(`dbAccess.query: Running Aggregation: ${JSON.stringify(pipeline)}`, 'dbug');
increment(collection);
return await db.collection(collection).aggregate(pipeline).toArray();
}
async function increment(target) { async function increment(target) {
log.out(`dbAccess.increment: Incrementing counter for: ${target}`, 'info'); log.out(`dbAccess.increment: Incrementing counter for: ${target}`, 'info');
await client.connect(); await client.connect();
@ -87,6 +105,8 @@ async function colCount(collection) {
module.exports = { module.exports = {
query, query,
queryProject,
queryAggregate,
increment, increment,
addUser, addUser,
userAtime, userAtime,

View File

@ -2,6 +2,7 @@ const log = require('../utils/log.utils');
const db = require('./dbAccess.services'); const db = require('./dbAccess.services');
const clean = require('../utils/sanitizer.utils'); const clean = require('../utils/sanitizer.utils');
const pis = require('../services/pis.services'); const pis = require('../services/pis.services');
const { filter } = require('compression');
async function findByHeadcodeToday(headcode) { async function findByHeadcodeToday(headcode) {
const sanitizedHeadcode = clean.removeNonAlphanumeric(headcode).toUpperCase(); const sanitizedHeadcode = clean.removeNonAlphanumeric(headcode).toUpperCase();
@ -56,30 +57,64 @@ async function findByHeadcode(date, headcode) {
scheduleEndDate: {$gte: searchDate}, scheduleEndDate: {$gte: searchDate},
daysRun: {$in: [shortDay]} daysRun: {$in: [shortDay]}
}; };
const queryData = await db.query('timetable', query); const pipeline = [
let trainData = await parseTrains(queryData); {
let preparedData = []; $match: query
for (let trainService of trainData) { },
// Search for PIS Code for each service if supported by PIS services {
if (pis.supported.includes(trainService?.operator)) { $project: {
const tiplocList = await getPublicStops(trainService?.stops); operator: 1,
//console.log(tiplocList.length); console.log(tiplocList); stops: {
if (tiplocList.length) { $concatArrays: [
const pisDetail = await pis.findByTiplocArray(tiplocList); [{ $first: '$stops'}],
trainService.pis = pisDetail?.[0]?.['code'] ?? 'None'; [{ $arrayElemAt: ['$stops', -1]}]
} else if (trainService.operator === 'GW' && !tiplocList.length) { ]
// Not in Service code - for GWR Only },
trainService.pis = '0015'; trainUid: 1,
stpIndicator: 1
} }
} }
preparedData.push(trainService); ];
const queryData = await db.queryAggregate('timetable', pipeline);
console.log(JSON.stringify(queryData));
let filteredData = filterServices(queryData);
return await filteredData;
}
async function findByTrainUid(uid, date = new Date()) {
let queryDate;
if (date === 'now') {
queryDate = new Date();
} else {
queryDate = date;
} }
return preparedData; const query = {
trainUid: uid,
scheduleStartDate: {$lte: queryDate},
scheduleEndDate: {$gte: queryDate}
};
const queryData = await db.query('timetable', query);
if (queryData.length === 0) {
return [];
}
let services;
services = await filterServices(queryData);
console.log(services);
let publicStops;
if (pis.supported.includes(services[0]?.operator)) {
publicStops = await getPublicStops(services[0]?.stops);
const pisCode = await pis.findByTiplocArray(publicStops);
services[0].pis = pisCode[0]?.code;
} else if ( services[0]?.operator === 'GW' && !publicStops.length) {
services[0].pis = '0015';
}
return services[0];
} }
module.exports = { module.exports = {
findByHeadcodeToday, findByHeadcodeToday,
findByHeadcode findByHeadcode,
findByTrainUid
}; };
/* Internal Functions, not to be exported */ /* Internal Functions, not to be exported */
@ -115,21 +150,9 @@ async function parseTrains(data) {
return parsedData; return parsedData;
} }
/* Queries using a trainUid and filters all schedules that async function filterServices(data) {
have been over-ridden by overlays, cancellations and new let stpIndicators = {}, filteredServices = [];
schedules. */ for (const serviceDetail of data) {
async function findByTrainUid(uid, date = new Date()) {
const query = {
trainUid: uid,
scheduleStartDate: {$lte: date},
scheduleEndDate: {$gte: date}
};
const queryData = await db.query('timetable', query);
if (queryData.length === 0) {
return [];
}
let stpIndicators = {};
for (const serviceDetail of queryData) {
const trainUid = serviceDetail['trainUid']; const trainUid = serviceDetail['trainUid'];
const stpIndicator = serviceDetail['stpIndicator']; const stpIndicator = serviceDetail['stpIndicator'];
if (!stpIndicators[trainUid]) { if (!stpIndicators[trainUid]) {
@ -153,30 +176,30 @@ async function findByTrainUid(uid, date = new Date()) {
stpIndicators[trainUid].hasP = true; stpIndicators[trainUid].hasP = true;
} }
} }
let preparedData = []; let preparedData;
for (const serviceDetail of queryData) { for (const serviceDetail of data) {
const trainUid = serviceDetail['trainUid']; const trainUid = serviceDetail['trainUid'];
const thisStpIndicators = stpIndicators[trainUid]; const thisStpIndicators = stpIndicators[trainUid];
const stpIndicator = serviceDetail['stpIndicator']; const stpIndicator = serviceDetail['stpIndicator'];
if (stpIndicator === 'C') { if (stpIndicator === 'C') {
return; break;
} }
if (stpIndicator === 'N' && if (stpIndicator === 'N' &&
!thisStpIndicators.hasC) { !thisStpIndicators.hasC) {
return serviceDetail; filteredServices.push(serviceDetail);
} else if (stpIndicator === 'O' && } else if (stpIndicator === 'O' &&
!thisStpIndicators.hasC && !thisStpIndicators.hasC &&
!thisStpIndicators.hasN) { !thisStpIndicators.hasN) {
return serviceDetail; filteredServices.push(serviceDetail);
} else if (stpIndicator === 'P' && } else if (stpIndicator === 'P' &&
!thisStpIndicators.hasC && !thisStpIndicators.hasC &&
!thisStpIndicators.hasN && !thisStpIndicators.hasN &&
!thisStpIndicators.hasO) { !thisStpIndicators.hasO) {
return serviceDetail; filteredServices.push(serviceDetail);
} }
} }
return preparedData; return filteredServices;
} }