Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

front: drop ISO8601Duration2sec() #10348

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import type { SearchResultItemOperationalPoint } from 'common/api/osrdEditoastApi';
import buildOpSearchQuery from 'modules/operationalPoint/helpers/buildOpSearchQuery';
import type { AppDispatch } from 'store';
import { Duration, addDurationToDate } from 'utils/duration';

import MacroEditorState, { type NodeIndexed } from './MacroEditorState';
import { addDurationToDate, deleteMacroNodeByDbId, getSavedMacroNodes } from './utils';
import { deleteMacroNodeByDbId, getSavedMacroNodes } from './utils';
import {
type PortDto,
type TimeLockDto,
Expand Down Expand Up @@ -414,17 +415,19 @@ const getNgeTrainrunSectionsWithNodes = (state: MacroEditorState, labels: LabelD
if (i === 0) {
sourceDeparture = createTimeLock(startTime);
} else if (sourceScheduleEntry && sourceScheduleEntry.arrival) {
const arrival = Duration.parse(sourceScheduleEntry.arrival);
const stopFor = sourceScheduleEntry.stop_for
? Duration.parse(sourceScheduleEntry.stop_for)
: Duration.zero;
sourceDeparture = createTimeLock(
addDurationToDate(
addDurationToDate(startTime, sourceScheduleEntry.arrival),
sourceScheduleEntry.stop_for || 'P0D'
)
addDurationToDate(addDurationToDate(startTime, arrival), stopFor)
);
}

let targetArrival = { ...DEFAULT_TIME_LOCK };
if (targetScheduleEntry && targetScheduleEntry.arrival) {
targetArrival = createTimeLock(addDurationToDate(startTime, targetScheduleEntry.arrival));
const arrival = Duration.parse(targetScheduleEntry.arrival);
targetArrival = createTimeLock(addDurationToDate(startTime, arrival));
}

const travelTime = { ...DEFAULT_TIME_LOCK };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
type SearchResultItemOperationalPoint,
} from 'common/api/osrdEditoastApi';
import type { AppDispatch } from 'store';
import { ISO8601Duration2sec } from 'utils/timeManipulation';

import type MacroEditorState from './MacroEditorState';
import type { NodeIndexed } from './MacroEditorState';
Expand Down Expand Up @@ -41,9 +40,6 @@ export const findOpFromPathItem = (
});
};

export const addDurationToDate = (date: Date, duration: string) =>
new Date(date.getTime() + ISO8601Duration2sec(duration) * 1000);

export const createMacroNode = async (
state: MacroEditorState,
dispatch: AppDispatch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import type {
TrainScheduleResult,
} from 'common/api/osrdEditoastApi';
import type { TrainScheduleWithDetails } from 'modules/trainschedule/components/Timetable/types';
import { Duration } from 'utils/duration';
import { jouleToKwh } from 'utils/physics';
import { formatKmValue } from 'utils/strings';
import { ISO8601Duration2sec } from 'utils/timeManipulation';
import { mapBy } from 'utils/types';

import { isScheduledPointsNotHonored, isTooFast } from '../utils';
Expand Down Expand Up @@ -70,7 +70,7 @@ const formatTrainScheduleSummaries = (
startTime,
stopsCount:
(trainSchedule.schedule?.filter(
(step) => step.stop_for && ISO8601Duration2sec(step.stop_for) > 0
(step) => step.stop_for && Duration.parse(step.stop_for).ms > 0
).length ?? 0) + 1, // +1 to take the final stop (destination) into account
speedLimitTag: trainSchedule.speed_limit_tag ?? null,
labels: trainSchedule.labels ?? [],
Expand Down
9 changes: 5 additions & 4 deletions front/src/applications/operationalStudies/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import type {
import getPathVoltages from 'modules/pathfinding/helpers/getPathVoltages';
import { ARRIVAL_TIME_ACCEPTABLE_ERROR_MS } from 'modules/timesStops/consts';
import { convertUTCDateToLocalDate, isoDateToMs } from 'utils/date';
import { mmToM, sToMs } from 'utils/physics';
import { Duration } from 'utils/duration';
import { mmToM } from 'utils/physics';
import { SMALL_INPUT_MAX_LENGTH } from 'utils/strings';
import { ISO8601Duration2sec, ms2sec } from 'utils/timeManipulation';
import { ms2sec } from 'utils/timeManipulation';

import { upsertMapWaypointsInOperationalPoints } from './helpers/upsertMapWaypointsInOperationalPoints';
import type {
Expand Down Expand Up @@ -240,9 +241,9 @@ export const isScheduledPointsNotHonored = (
`No matching index found for schedule ${schedule} on trainSchedule ${trainSchedule}`
);
}
const arrivalTimeInMs = sToMs(ISO8601Duration2sec(schedule.arrival));
const arrival = Duration.parse(schedule.arrival);
return (
Math.abs(arrivalTimeInMs - trainSummary.path_item_times_final[matchindIndex]) >=
Math.abs(arrival.ms - trainSummary.path_item_times_final[matchindIndex]) >=
ARRIVAL_TIME_ACCEPTABLE_ERROR_MS
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import {
type TrainScheduleBase,
} from 'common/api/osrdEditoastApi';
import type { SpeedRanges } from 'reducers/simulationResults/types';
import { Duration } from 'utils/duration';
import { mmToM, msToKmhRounded } from 'utils/physics';
import { ISO8601Duration2sec, ms2sec } from 'utils/timeManipulation';
import { ms2sec } from 'utils/timeManipulation';

export function massWithOneDecimal(number: number) {
return Math.round(number / 100) / 10;
Expand Down Expand Up @@ -127,7 +128,7 @@ export const formatOperationalPoints = (
(step) => step.at === correspondingStep.id
);
if (correspondingSchedule && correspondingSchedule.stop_for) {
stepDuration = ISO8601Duration2sec(correspondingSchedule.stop_for);
stepDuration = ms2sec(Duration.parse(correspondingSchedule.stop_for).ms);
}
}

Expand Down
23 changes: 12 additions & 11 deletions front/src/modules/timesStops/helpers/arrivalTime.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
/* eslint-disable import/prefer-default-export */
import { dateToHHMMSS } from 'utils/date';
import { ISO8601Duration2sec, calculateTimeDifferenceInDays } from 'utils/timeManipulation';
import { Duration, addDurationToDate } from 'utils/duration';
import { calculateTimeDifferenceInDays } from 'utils/timeManipulation';

import type { ScheduleEntry, TimeExtraDays } from '../types';

const computeDayTimeFromStartTime = (
startDatetime: Date,
duration: number, // seconds
duration: Duration,
previousDatetime: Date
): { timeExtraDay: TimeExtraDays; previousTime: Date } => {
const arrivalDatetime = new Date(startDatetime.getTime() + duration * 1000);
const arrivalDatetime = addDurationToDate(startDatetime, duration);

const isAfterMidnight = arrivalDatetime.getDate() !== previousDatetime.getDate();

Expand All @@ -33,29 +34,29 @@ export const computeInputDatetimes = (
let departure: TimeExtraDays | undefined;
let refDate = lastReferenceDate;

let arrivalInSeconds;
let arrivalDuration;
// if is departure, use the startDatetime
if (isDeparture) {
arrivalInSeconds = 0;
arrivalDuration = Duration.zero;
} else if (schedule?.arrival) {
arrivalInSeconds = ISO8601Duration2sec(schedule.arrival); // duration from startTime
arrivalDuration = Duration.parse(schedule.arrival); // duration from startTime
}

if (arrivalInSeconds !== undefined) {
theoreticalArrival = new Date(startDatetime.getTime() + arrivalInSeconds * 1000);
if (arrivalDuration) {
theoreticalArrival = addDurationToDate(startDatetime, arrivalDuration);
const { timeExtraDay, previousTime } = computeDayTimeFromStartTime(
startDatetime,
arrivalInSeconds,
arrivalDuration,
refDate
);
arrival = timeExtraDay;
refDate = previousTime;

if (schedule?.stop_for) {
const departureInSeconds = arrivalInSeconds + ISO8601Duration2sec(schedule.stop_for);
const stopFor = Duration.parse(schedule.stop_for);
const resultDeparture = computeDayTimeFromStartTime(
startDatetime,
departureInSeconds,
arrivalDuration.add(stopFor),
refDate
);
departure = resultDeparture.timeExtraDay;
Expand Down
9 changes: 5 additions & 4 deletions front/src/modules/timesStops/helpers/scheduleData.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable import/prefer-default-export */
import { dateToHHMMSS } from 'utils/date';
import { ISO8601Duration2sec } from 'utils/timeManipulation';
import { Duration, addDurationToDate } from 'utils/duration';
import { ms2sec } from 'utils/timeManipulation';

import type { ScheduleEntry } from '../types';
import { receptionSignalToSignalBooleans } from './utils';
Expand All @@ -24,11 +25,11 @@ export const formatSchedule = (arrivalTime: Date, schedule?: ScheduleEntry) => {
};
}

const stopForSeconds = ISO8601Duration2sec(schedule.stop_for);
const stopFor = Duration.parse(schedule.stop_for);

return {
stopFor: `${stopForSeconds}`,
calculatedDeparture: dateToHHMMSS(new Date(arrivalTime.getTime() + stopForSeconds * 1000)),
stopFor: `${ms2sec(stopFor.ms)}`,
calculatedDeparture: dateToHHMMSS(addDurationToDate(arrivalTime, stopFor)),
...receptionSignalToSignalBooleans(schedule.reception_signal),
};
};
22 changes: 1 addition & 21 deletions front/src/utils/__tests__/timeManipulation.spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,6 @@
import { describe, it, expect } from 'vitest';

import { ISO8601Duration2sec, calculateTimeDifferenceInDays } from 'utils/timeManipulation';

describe('ISO8601Duration2sec', () => {
it('should handle only seconds', () => {
expect(ISO8601Duration2sec('PT5S')).toEqual(5);
});
it('should handle only min', () => {
// 1min = 60s
expect(ISO8601Duration2sec('PT5M')).toEqual(300);
});
it('should handle only hours', () => {
// 1h = 60min
expect(ISO8601Duration2sec('PT1H')).toEqual(3600);
});
it('should handle hours, mins and seconds', () => {
expect(ISO8601Duration2sec('PT1H1M1S')).toEqual(3661);
});
it('should handle hours and seconds without min', () => {
expect(ISO8601Duration2sec('PT1H1S')).toEqual(3601);
});
});
import { calculateTimeDifferenceInDays } from 'utils/timeManipulation';

describe('calculateTimeDifferenceInDays', () => {
it('should handle undefined dates', () => {
Expand Down
6 changes: 6 additions & 0 deletions front/src/utils/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,10 @@ export class Duration {
toJSON() {
return this.toISOString();
}

add(other: Duration) {
return new Duration(this.ms + other.ms);
}
}

export const addDurationToDate = (date: Date, dur: Duration) => new Date(date.getTime() + dur.ms);
8 changes: 0 additions & 8 deletions front/src/utils/timeManipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,6 @@ export function calculateTimeDifferenceInDays(datetime1?: Date, datetime2?: Date
return dayjs.duration(date2.getTime() - date1.getTime()).asDays();
}

/**
* Parse ISO8601 duration, for instance "PT11H9M8S" (11h, 9min and 8s) to seconds
*/
export function ISO8601Duration2sec(isoDuration: string) {
const durationDictionnary = dayjs.duration(isoDuration);
return durationDictionnary.asSeconds();
}

/**
* converts a value in seconds to a timeString "HH:MM"
*
Expand Down
Loading