-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathutils.ts
346 lines (316 loc) · 11.4 KB
/
utils.ts
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
/* eslint-disable @typescript-eslint/no-use-before-define */
import dayjs from 'dayjs';
import type { TFunction } from 'i18next';
import { round, isEqual, isNil } from 'lodash';
import { keyColumn, createTextColumn } from 'react-datasheet-grid';
import type { ReceptionSignal } from 'common/api/osrdEditoastApi';
import type { IsoDurationString, TimeString } from 'common/types';
import { matchPathStepAndOp } from 'modules/pathfinding/utils';
import type { SuggestedOP } from 'modules/trainschedule/components/ManageTrainSchedule/types';
import type { PathStep } from 'reducers/osrdconf/types';
import { NO_BREAK_SPACE } from 'utils/strings';
import {
calculateTimeDifferenceInSeconds,
datetime2sec,
durationInSeconds,
formatDurationAsISO8601,
sec2time,
SECONDS_IN_A_DAY,
secToHoursString,
time2sec,
} from 'utils/timeManipulation';
import { marginRegExValidation, MarginUnit } from '../consts';
import { TableType, type TimeExtraDays, type TimesStopsInputRow } from '../types';
const matchPathStepAndOpWithKP = (step: PathStep, op: SuggestedOP) => {
if (!matchPathStepAndOp(step, op)) {
return step.id === op.pathStepId;
}
// We match the kp in case two OPs have the same uic+ch (can happen when the
// infra is imported)
if ('uic' in step || 'trigram' in step) {
return step.kp === op.kp;
}
return true;
};
export const formatSuggestedViasToRowVias = (
operationalPoints: (SuggestedOP & { isWaypoint?: boolean })[],
pathSteps: PathStep[],
t: TFunction<'timesStops', undefined>,
startTime?: Date,
tableType?: TableType
): TimesStopsInputRow[] => {
const formattedOps = [...operationalPoints];
// If the origin is in the ops and isn't the first operational point, we need
// to move it to the first position
const origin = pathSteps[0];
const originIndexInOps = origin
? operationalPoints.findIndex((op) => matchPathStepAndOpWithKP(origin, op))
: -1;
if (originIndexInOps !== -1) {
[formattedOps[0], formattedOps[originIndexInOps]] = [
formattedOps[originIndexInOps],
formattedOps[0],
];
}
// Ditto: destination should be last
const dest = pathSteps[pathSteps.length - 1];
const destIndexInOps = dest
? operationalPoints.findIndex((op) => matchPathStepAndOpWithKP(dest, op))
: -1;
if (destIndexInOps !== -1) {
const lastOpIndex = formattedOps.length - 1;
[formattedOps[lastOpIndex], formattedOps[destIndexInOps]] = [
formattedOps[destIndexInOps],
formattedOps[lastOpIndex],
];
}
return formattedOps.map((op, i) => {
const pathStep = pathSteps.find((step) => matchPathStepAndOpWithKP(step, op));
const { name } = pathStep || op;
const objectToUse = tableType === TableType.Input ? pathStep : op;
const { arrival, receptionSignal, stopFor, theoreticalMargin } = objectToUse || {};
const isMarginValid = theoreticalMargin ? marginRegExValidation.test(theoreticalMargin) : true;
const durationArrivalTime = i === 0 ? 'PT0S' : arrival;
const arrivalInSeconds = durationArrivalTime ? time2sec(durationArrivalTime) : null;
const formattedArrival = calculateStepTimeAndDays(startTime, durationArrivalTime);
const departureTime =
stopFor && arrivalInSeconds
? secToHoursString(arrivalInSeconds + Number(stopFor), { withSeconds: true })
: undefined;
const formattedDeparture: TimeExtraDays | undefined = departureTime
? { time: departureTime }
: undefined;
const { receptionSignal: _opReceptionSignal, ...filteredOp } = op;
const { shortSlipDistance, onStopSignal } = receptionSignalToSignalBooleans(receptionSignal);
return {
...filteredOp,
isMarginValid,
arrival: formattedArrival,
departure: formattedDeparture,
onStopSignal,
name: name || t('waypoint', { id: filteredOp.pathStepId }),
shortSlipDistance,
stopFor,
theoreticalMargin,
isWaypoint: op.isWaypoint || pathStep !== undefined,
};
});
};
const getDigits = (unit: string | undefined) =>
unit === MarginUnit.second || unit === MarginUnit.percent ? 0 : 1;
export function formatDigitsAndUnit(fullValue: string | number | undefined, unit?: string) {
if (fullValue === undefined) {
return '';
}
if (typeof fullValue === 'number') {
return `${round(Number(fullValue), getDigits(unit))}${NO_BREAK_SPACE}${unit}`;
}
const splitValue = fullValue.match(marginRegExValidation);
if (!splitValue) {
return '';
}
const extractedValue = Number(splitValue[1]);
const extractedUnit = splitValue[3];
const digits = getDigits(extractedUnit);
return `${round(extractedValue, digits)}${NO_BREAK_SPACE}${extractedUnit}`;
}
export function disabledTextColumn(
key: string,
title: string,
options?: Parameters<typeof createTextColumn>[0]
) {
return {
...keyColumn(key, createTextColumn(options)),
title,
disabled: true,
};
}
/**
* Synchronizes arrival, departure and stop times.
* updates onStopSignal
* updates isMarginValid and theoreticalMargin
*/
export function updateRowTimesAndMargin(
rowData: TimesStopsInputRow,
previousRowData: TimesStopsInputRow,
op: { fromRowIndex: number },
allWaypointsLength: number
): TimesStopsInputRow {
const newRowData = { ...rowData };
if (
!isEqual(newRowData.arrival, previousRowData.arrival) ||
!isEqual(newRowData.departure, previousRowData.departure)
) {
if (newRowData.departure?.time && newRowData.arrival?.time) {
newRowData.stopFor = String(
durationInSeconds(time2sec(newRowData.arrival.time), time2sec(newRowData.departure.time))
);
} else if (newRowData.departure) {
if (!previousRowData.departure) {
newRowData.arrival = {
time: sec2time(time2sec(newRowData.departure.time) - Number(newRowData.stopFor)),
};
} else {
newRowData.departure = undefined;
}
} else if (newRowData.arrival && previousRowData.departure) {
// we just erased departure value
newRowData.stopFor = undefined;
}
}
if (
!newRowData.stopFor &&
newRowData.onStopSignal &&
op.fromRowIndex !== allWaypointsLength - 1
) {
newRowData.onStopSignal = false;
}
newRowData.isMarginValid = !(
newRowData.theoreticalMargin && !marginRegExValidation.test(newRowData.theoreticalMargin)
);
if (newRowData.isMarginValid && op.fromRowIndex === 0) {
newRowData.arrival = undefined;
// As we put 0% by default for origin's margin, if the user removes a margin without
// replacing it to 0% (undefined), we change it to 0%
if (!newRowData.theoreticalMargin) {
newRowData.theoreticalMargin = '0%';
}
}
// Remove second unit in stopFor if inputted by mistake
if (newRowData.stopFor && /^[0-9]+ *s$/i.test(newRowData.stopFor)) {
newRowData.stopFor = newRowData.stopFor.replace(/ *s$/i, '');
}
return newRowData;
}
/**
* This function is called before comparing rows to prevent a change from undefined to null (or the reverse)
* from being treated as an actual update of a row (otherwise changes would occur on deletion of an undefined field)
*/
export function normalizeNullablesInRow(row: TimesStopsInputRow): TimesStopsInputRow {
const normalizedRow = { ...row };
if (normalizedRow.stopFor === null) {
normalizedRow.stopFor = undefined;
}
if (normalizedRow.theoreticalMargin === null) {
normalizedRow.theoreticalMargin = undefined;
}
return normalizedRow;
}
/**
* This function goes through the whole array of path waypoints
* and updates the number of days since departure.
*/
export function updateDaySinceDeparture(
pathWaypointRows: TimesStopsInputRow[],
startTime?: Date,
{ keepFirstIndexArrival = false } = {}
): TimesStopsInputRow[] {
let currentDaySinceDeparture = 0;
let previousTime = startTime ? datetime2sec(startTime) : Number.NEGATIVE_INFINITY;
return pathWaypointRows.map((pathWaypoint, index) => {
const { arrival, stopFor } = pathWaypoint;
const arrivalInSeconds = arrival?.time ? time2sec(arrival.time) : null;
let formattedArrival: TimeExtraDays | undefined;
if (arrivalInSeconds !== null) {
const isMidnight = arrival?.time === '00:00:00';
if ((arrivalInSeconds < previousTime || isMidnight) && !(isMidnight && index === 0)) {
currentDaySinceDeparture += 1;
formattedArrival = {
time: arrival!.time,
daySinceDeparture: currentDaySinceDeparture,
dayDisplayed: true,
};
} else {
formattedArrival = {
time: arrival!.time,
daySinceDeparture: currentDaySinceDeparture,
};
}
previousTime = isMidnight ? 0 : arrivalInSeconds;
}
let formattedDeparture: TimeExtraDays | undefined;
if (stopFor && arrivalInSeconds !== null) {
const departureInSeconds = (arrivalInSeconds + Number(stopFor)) % SECONDS_IN_A_DAY;
const isAfterMidnight = departureInSeconds < previousTime;
const isDepartureMidnight = departureInSeconds === 0;
if (isAfterMidnight || isDepartureMidnight) {
currentDaySinceDeparture += 1;
formattedDeparture = {
time: secToHoursString(departureInSeconds, { withSeconds: true }),
daySinceDeparture: currentDaySinceDeparture,
dayDisplayed: true,
};
} else {
formattedDeparture = {
time: secToHoursString(departureInSeconds, { withSeconds: true }),
daySinceDeparture: currentDaySinceDeparture,
};
}
previousTime = departureInSeconds;
}
return {
...pathWaypoint,
arrival: keepFirstIndexArrival || index > 0 ? formattedArrival : undefined,
departure: formattedDeparture,
};
});
}
export function durationSinceStartTime(
startTime?: Date,
stepTimeDays?: TimeExtraDays
): IsoDurationString | null {
if (!startTime || !stepTimeDays?.time || stepTimeDays?.daySinceDeparture === undefined) {
return null;
}
const start = dayjs(startTime);
const step = dayjs(`${start.format('YYYY-MM-DD')}T${stepTimeDays.time}`).add(
stepTimeDays.daySinceDeparture,
'day'
);
return formatDurationAsISO8601(
calculateTimeDifferenceInSeconds(start.toISOString(), step.toISOString())
);
}
export function calculateStepTimeAndDays(
startTime?: Date | null,
isoDuration?: IsoDurationString | null
): TimeExtraDays | undefined {
if (!startTime || !isoDuration) {
return undefined;
}
const start = dayjs(startTime);
const duration = dayjs.duration(isoDuration);
const waypointArrivalTime = start.add(duration);
const daySinceDeparture = waypointArrivalTime.diff(start, 'day');
const time: TimeString = waypointArrivalTime.format('HH:mm:ss');
return {
time,
daySinceDeparture,
};
}
/** Convert onStopSignal boolean to receptionSignal enum */
export function onStopSignalToReceptionSignal(
onStopSignal?: boolean,
shortSlipDistance?: boolean
): ReceptionSignal | undefined {
if (isNil(onStopSignal)) {
return undefined;
}
if (onStopSignal === true) {
return shortSlipDistance ? 'SHORT_SLIP_STOP' : 'STOP';
}
return 'OPEN';
}
/** Convert receptionSignal enum to onStopSignal boolean */
export function receptionSignalToSignalBooleans(receptionSignal?: ReceptionSignal) {
if (isNil(receptionSignal)) {
return { shortSlipDistance: undefined, onStopSignal: undefined };
}
if (receptionSignal === 'STOP') {
return { shortSlipDistance: false, onStopSignal: true };
}
if (receptionSignal === 'SHORT_SLIP_STOP') {
return { shortSlipDistance: true, onStopSignal: true };
}
return { shortSlipDistance: false, onStopSignal: false };
}