-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathImportTrainScheduleConfig.tsx
470 lines (425 loc) · 16.1 KB
/
ImportTrainScheduleConfig.tsx
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import { useState, useContext } from 'react';
import { Download, Search } from '@osrd-project/ui-icons';
import { isEmpty } from 'lodash';
import { useTranslation } from 'react-i18next';
import nextId from 'react-id-generator';
import type {
ImportStation,
ImportedTrainSchedule,
TrainScheduleImportConfig,
Step,
CichDictValue,
} from 'applications/operationalStudies/types';
import { getGraouTrainSchedules } from 'common/api/graouApi';
import { type TrainScheduleBase } from 'common/api/osrdEditoastApi';
import InputSNCF from 'common/BootstrapSNCF/InputSNCF';
import { ModalContext } from 'common/BootstrapSNCF/ModalSNCF/ModalProvider';
import StationCard from 'common/StationCard';
import UploadFileModal from 'common/uploadFileModal';
import StationSelector from 'modules/trainschedule/components/ImportTrainSchedule/ImportTrainScheduleStationSelector';
import { setFailure } from 'reducers/main';
import { useAppDispatch } from 'store';
import { formatIsoDate } from 'utils/date';
import {
handleFileReadingError,
handleUnsupportedFileType,
processJsonFile,
processXmlFile,
} from '../ManageTrainSchedule/helpers/handleParseFiles';
interface ImportTrainScheduleConfigProps {
setTrainsList: (trainsList: ImportedTrainSchedule[]) => void;
setIsLoading: (isLoading: boolean) => void;
setTrainsJsonData: (trainsJsonData: TrainScheduleBase[]) => void;
setTrainsXmlData: (trainsXmlData: ImportedTrainSchedule[]) => void;
}
const ImportTrainScheduleConfig = ({
setTrainsList,
setIsLoading,
setTrainsJsonData,
setTrainsXmlData,
}: ImportTrainScheduleConfigProps) => {
const { t } = useTranslation(['operationalStudies/importTrainSchedule']);
const [from, setFrom] = useState<ImportStation | undefined>();
const [fromSearchString, setFromSearchString] = useState('');
const [to, setTo] = useState<ImportStation | undefined>();
const [toSearchString, setToSearchString] = useState('');
const [date, setDate] = useState(formatIsoDate(new Date()));
const [startTime, setStartTime] = useState('00:00');
const [endTime, setEndTime] = useState('23:59');
const dispatch = useAppDispatch();
const { openModal, closeModal } = useContext(ModalContext);
function validateImportedTrainSchedules(
importedTrainSchedules: Record<string, unknown>[]
): ImportedTrainSchedule[] | null {
const isInvalidTrainSchedules = importedTrainSchedules.some((trainSchedule) => {
if (
['trainNumber', 'rollingStock', 'departureTime', 'arrivalTime', 'departure', 'steps'].some(
(key) => !(key in trainSchedule)
) ||
!Array.isArray(trainSchedule.steps)
) {
return true;
}
const hasInvalidSteps = trainSchedule.steps.some((step) =>
['arrivalTime', 'departureTime', 'uic', 'name', 'trigram', 'latitude', 'longitude'].some(
(key) => !(key in step)
)
);
return hasInvalidSteps;
});
if (isInvalidTrainSchedules) {
dispatch(
setFailure({
name: t('errorMessages.error'),
message: t('errorMessages.errorImport'),
})
);
return null;
}
return importedTrainSchedules as ImportedTrainSchedule[];
}
function updateTrainSchedules(importedTrainSchedules: ImportedTrainSchedule[]) {
// For each train schedule, we add the duration and tracks of each step
const trainsSchedules = importedTrainSchedules.map((trainSchedule) => {
const stepsWithDuration = trainSchedule.steps.map((step) => {
// calcul duration in seconds between step arrival and departure
// in case of arrival and departure are the same, we set duration to 0
// for the step arrivalTime is before departureTime because the train first goes to the station and then leaves it
const duration = Math.round(
(new Date(step.departureTime).getTime() - new Date(step.arrivalTime).getTime()) / 1000
);
return {
...step,
duration,
};
});
return {
...trainSchedule,
steps: stepsWithDuration,
};
});
setTrainsList(trainsSchedules);
}
async function getTrainsFromOpenData(config: TrainScheduleImportConfig) {
setTrainsList([]);
setIsLoading(true);
setTrainsJsonData([]);
setTrainsXmlData([]);
const result = await getGraouTrainSchedules(config);
const importedTrainSchedules = validateImportedTrainSchedules(result);
if (importedTrainSchedules && !isEmpty(importedTrainSchedules)) {
updateTrainSchedules(importedTrainSchedules);
}
setIsLoading(false);
}
function defineConfig() {
let error = false;
if (!from) {
dispatch(
setFailure({ name: t('errorMessages.error'), message: t('errorMessages.errorNoFrom') })
);
}
if (!to) {
dispatch(
setFailure({ name: t('errorMessages.error'), message: t('errorMessages.errorNoTo') })
);
}
if (!date) {
dispatch(
setFailure({ name: t('errorMessages.error'), message: t('errorMessages.errorNoDate') })
);
}
if (JSON.stringify(from) === JSON.stringify(to)) {
dispatch(
setFailure({ name: t('errorMessages.error'), message: t('errorMessages.errorSameFromTo') })
);
error = true;
}
if (from && to && date && !error) {
getTrainsFromOpenData({
from,
to,
date,
startTime,
endTime,
});
}
}
const extractCiChCode = (code: string) => {
const [ciCode, chCode] = code.split('/');
return { ciCode: Number(ciCode), chCode };
};
const cleanTimeFormat = (time: string): string => time.replace(/\.0$/, ''); // Remove the '.0' if it's at the end of the time string
const buildSteps = (
ocpTTs: Element[],
cichDict: Record<string, CichDictValue>,
startDate: string
): Step[] =>
ocpTTs
.map((ocpTT): Step | null => {
const ocpRef = ocpTT.getAttribute('ocpRef');
const times = ocpTT.getElementsByTagName('times')[0];
const isLastOcp = ocpTT === ocpTTs.at(-1);
const ocpType = ocpTT.getAttribute('ocpType');
let departureTime = times?.getAttribute('departure') || '';
let arrivalTime = ocpType === 'pass' ? departureTime : times?.getAttribute('arrival') || '';
arrivalTime = cleanTimeFormat(arrivalTime);
departureTime = cleanTimeFormat(departureTime);
if (!ocpRef) {
console.error('ocpRef is null or undefined');
return null;
}
const operationalPoint = cichDict[ocpRef];
if (!operationalPoint) {
return null; // Skip step if not found in the cichDict
}
//! We add 87 to the CI code to create the UIC. It is France specific and will break if used in other countries.
const uic = Number(`87${operationalPoint.ciCode}`); // Add 87 to the CI code to create the UIC
const { chCode } = operationalPoint;
const formattedArrivalTime = `${startDate} ${arrivalTime}`;
const formattedDepartureTime = `${startDate} ${departureTime}`;
let stopFor: number | undefined;
const arrivalDate = new Date(`${startDate}T${arrivalTime}`);
const departureDate = new Date(`${startDate}T${departureTime}`);
if (ocpType === 'stop') {
if (arrivalTime && departureTime) {
stopFor = Math.round((departureDate.getTime() - arrivalDate.getTime()) / 1000);
} else {
stopFor = 0;
}
} else if (ocpType === 'pass') {
if (isLastOcp) {
stopFor = 0;
}
}
return {
id: nextId(),
uic,
chCode,
name: ocpRef,
arrivalTime: formattedArrivalTime,
departureTime: formattedDepartureTime,
duration: stopFor,
} as Step;
})
.filter((step): step is Step => step !== null);
const mapTrainNames = (trainSchedules: ImportedTrainSchedule[], trains: Element[]) => {
const trainPartToTrainMap: Record<string, string> = {};
trains.forEach((train) => {
const trainPartRef = train.getElementsByTagName('trainPartRef')[0]?.getAttribute('ref');
const trainName = train.getAttribute('name') || '';
if (trainPartRef) {
trainPartToTrainMap[trainPartRef] = trainName;
}
});
const updatedTrainSchedules = trainSchedules.map((schedule) => {
const mappedTrainNumber = trainPartToTrainMap[schedule.trainNumber] || schedule.trainNumber;
return {
...schedule,
trainNumber: mappedTrainNumber,
};
});
return updatedTrainSchedules;
};
const parseRailML = async (xmlDoc: Document): Promise<ImportedTrainSchedule[]> => {
const trainSchedules: ImportedTrainSchedule[] = [];
// Initialize localCichDict
const localCichDict: Record<string, CichDictValue> = {};
const infrastructures = Array.from(xmlDoc.getElementsByTagName('infrastructure'));
infrastructures.forEach((infrastructure) => {
const ocps = Array.from(infrastructure.getElementsByTagName('ocp'));
ocps.forEach((ocp) => {
const id = ocp.getAttribute('id');
const code = ocp.getAttribute('code');
if (id && code) {
const { ciCode, chCode } = extractCiChCode(code);
localCichDict[id] = { ciCode, chCode };
}
});
});
const trainParts = Array.from(xmlDoc.getElementsByTagName('trainPart'));
const period = xmlDoc.getElementsByTagName('timetablePeriod')[0];
const startDate = period ? period.getAttribute('startDate') : null;
if (!startDate) {
console.error('Start Date not found in the timetablePeriod.');
return trainSchedules;
}
trainParts.forEach((train) => {
const trainNumber = train.getAttribute('id') || '';
const ocpSteps = Array.from(train.getElementsByTagName('ocpTT'));
const formationTT = train.getElementsByTagName('formationTT')[0];
const rollingStockViriato = formationTT?.getAttribute('formationRef');
const firstOcpTT = ocpSteps[0];
const firstDepartureTime = firstOcpTT
.getElementsByTagName('times')[0]
?.getAttribute('departure');
const firstDepartureTimeformatted = firstDepartureTime && cleanTimeFormat(firstDepartureTime);
const lastOcpTT = ocpSteps[ocpSteps.length - 1];
const lastDepartureTime =
lastOcpTT.getElementsByTagName('times')[0]?.getAttribute('departure') ||
lastOcpTT.getElementsByTagName('times')[0]?.getAttribute('arrival');
const lastDepartureTimeformatted = lastDepartureTime && cleanTimeFormat(lastDepartureTime);
// Build steps using the fully populated localCichDict
const adaptedSteps = buildSteps(ocpSteps, localCichDict, startDate);
const trainSchedule: ImportedTrainSchedule = {
trainNumber,
rollingStock: rollingStockViriato, // RollingStocks in viriato files rarely have the correct format
departureTime: `${startDate} ${firstDepartureTimeformatted}`,
arrivalTime: `${startDate} ${lastDepartureTimeformatted}`,
departure: '', // Default for testing
steps: adaptedSteps,
};
trainSchedules.push(trainSchedule);
});
const trains = Array.from(xmlDoc.getElementsByTagName('train'));
const updatedTrainSchedules = mapTrainNames(trainSchedules, trains);
setTrainsXmlData(updatedTrainSchedules);
return updatedTrainSchedules;
};
const importFile = async (file: File) => {
closeModal();
setTrainsList([]);
const fileName = file.name.toLowerCase();
const fileExtension = fileName.split('.').pop();
try {
const fileContent = await file.text();
if (fileExtension === 'json') {
processJsonFile(fileContent, setTrainsJsonData, dispatch);
} else if (fileExtension === 'xml' || fileExtension === 'railml') {
processXmlFile(fileContent, parseRailML, updateTrainSchedules, dispatch);
} else {
handleUnsupportedFileType(dispatch);
}
} catch (error) {
handleFileReadingError(error as Error);
}
};
return (
<>
<div className="container-fluid row no-gutters mb-2">
<div className="col-lg-6 station-selector sm-gutters">
<div className="mb-2">
<div className="osrd-config-item-container osrd-config-item-from">
<h2>{t('from')}</h2>
{from ? (
<div
className="result-station-selected"
aria-label={t('from')}
onClick={() => setFrom(undefined)}
role="button"
tabIndex={0}
>
<StationCard station={from} fixedHeight />
</div>
) : (
<StationSelector
id="fromSearch"
onSelect={setFrom}
term={fromSearchString}
setTerm={setFromSearchString}
/>
)}
</div>
</div>
</div>
<div className="col-lg-6 station-selector sm-gutters">
<div className="mb-2">
<div className="osrd-config-item-container osrd-config-item-to">
<h2>{t('to')}</h2>
{to ? (
<div
className="result-station-selected"
aria-label={t('to')}
onClick={() => setTo(undefined)}
role="button"
tabIndex={0}
>
<StationCard station={to} fixedHeight />
</div>
) : (
<StationSelector
id="toSearch"
onSelect={setTo}
term={toSearchString}
setTerm={setToSearchString}
/>
)}
</div>
</div>
</div>
</div>
<div className="container-fluid mb-2">
<div className="row no-gutters">
<div className="col-lg-10 col-10">
<div className="osrd-config-item-container osrd-config-item-datetime">
<h2>{t('datetime')}</h2>
<div className="mb-2">
<InputSNCF
id="date"
type="date"
value={date}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDate(e.target.value)}
sm
noMargin
step={0}
unit={t('date')}
/>
</div>
<div className="row no-gutters">
<div className="col-6 sm-gutters">
<InputSNCF
id="startTime"
type="time"
value={startTime}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setStartTime(e.target.value)
}
sm
noMargin
step={0}
unit={t('startTime')}
/>
</div>
<div className="col-6 sm-gutters">
<InputSNCF
id="endTime"
type="time"
value={endTime}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setEndTime(e.target.value)
}
sm
noMargin
step={0}
unit={t('endTime')}
/>
</div>
</div>
</div>
</div>
<div className="col-lg-2 col-2 d-flex flex-column no-gutters pl-1">
<button
type="button"
className="btn btn-sm btn-primary btn-block h-100"
aria-label={t('searchTimetable')}
title={t('searchTimetable')}
onClick={defineConfig}
>
<Search />
</button>
<button
type="button"
className="btn btn-sm btn-secondary btn-block h-100"
aria-label={t('importTimetable')}
title={t('importTimetable')}
onClick={() => openModal(<UploadFileModal handleSubmit={importFile} />)}
>
<Download />
</button>
</div>
</div>
</div>
</>
);
};
export default ImportTrainScheduleConfig;