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: use Date instead of string in OsrdConfState.startTime #9954

Merged
merged 4 commits into from
Dec 20, 2024
Merged
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 @@ -123,7 +123,10 @@ const useLinkedTrainSearch = () => {

const originDetails = await getExtremityDetails(result.path.at(0)!);
const destinationDetails = await getExtremityDetails(result.path.at(-1)!);
const computedOpSchedules = computeOpSchedules(result.start_time, msFromStartTime);
const computedOpSchedules = computeOpSchedules(
new Date(result.start_time),
msFromStartTime
);

if (!originDetails || !destinationDetails) return undefined;
return {
Expand Down
18 changes: 7 additions & 11 deletions front/src/applications/stdcm/utils/computeOpSchedules.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
extractDateAndTimefromISO,
addDurationToIsoDate,
substractDurationToIsoDate,
} from 'utils/date';
import { extractDateAndTime, addDurationToDate, subtractDurationFromDate } from 'utils/date';

/**
* Computes the operation schedules for a given start time and duration.
Expand All @@ -18,13 +14,13 @@ import {
* Note: A margin of 1800 seconds (30 minutes) is applied to the departure and arrival times to allow for necessary
* activities such as preparation for the next departure.
*/
const computeOpSchedules = (startTime: string, msFromStartTime: number) => {
const { arrivalDate: originDate, arrivalTime: originTime } = extractDateAndTimefromISO(
const computeOpSchedules = (startTime: Date, msFromStartTime: number) => {
const { arrivalDate: originDate, arrivalTime: originTime } = extractDateAndTime(
startTime,
'DD/MM/YY'
);
const destinationArrivalTime = addDurationToIsoDate(startTime, msFromStartTime, 'millisecond');
const { arrivalDate: destinationDate, arrivalTime: destinationTime } = extractDateAndTimefromISO(
const destinationArrivalTime = addDurationToDate(startTime, msFromStartTime, 'millisecond');
const { arrivalDate: destinationDate, arrivalTime: destinationTime } = extractDateAndTime(
destinationArrivalTime,
'DD/MM/YY'
);
Expand All @@ -33,12 +29,12 @@ const computeOpSchedules = (startTime: string, msFromStartTime: number) => {
origin: {
date: originDate,
time: originTime,
isoArrivalTime: substractDurationToIsoDate(startTime, 1800),
isoArrivalTime: subtractDurationFromDate(startTime, 1800).toISOString(),
},
destination: {
date: destinationDate,
time: destinationTime,
isoArrivalTime: addDurationToIsoDate(destinationArrivalTime, 1800),
isoArrivalTime: addDurationToDate(destinationArrivalTime, 1800).toISOString(),
},
};
};
Expand Down
9 changes: 0 additions & 9 deletions front/src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,6 @@ export const DATA_TYPES = {
*/
export type TimeString = string;

/**
* A string with the complete iso format
*
* @example "2024-08-08T10:12:46.209Z"
* @example "2024-08-08T10:12:46Z"
* @example "2024-08-08T10:12:46+02:00"
*/
export type IsoDateTimeString = string;

/**
* A ISO 8601 duration string
* @example "PT3600S"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { useStoreDataForRollingStockSelector } from 'modules/rollingStock/compon
import trainNameWithNum from 'modules/trainschedule/components/ManageTrainSchedule/helpers/trainNameHelper';
import { setFailure, setSuccess } from 'reducers/main';
import { useAppDispatch } from 'store';
import { formatToIsoDate, isoDateToMs, isoDateWithTimezoneToSec } from 'utils/date';
import { isoDateToMs, isoDateWithTimezoneToSec } from 'utils/date';
import { castErrorToFailure } from 'utils/error';
import { sec2time } from 'utils/timeManipulation';

Expand Down Expand Up @@ -58,16 +58,10 @@ const AddTrainScheduleButton = ({
let actualTrainCount = 1;

for (let nb = 1; nb <= trainCount; nb += 1) {
const newStartTimeString = formatToIsoDate(
formattedStartTimeMs + 1000 * 60 * trainDelta * (nb - 1)
);
const newStartTime = new Date(formattedStartTimeMs + 1000 * 60 * trainDelta * (nb - 1));
const trainName = trainNameWithNum(baseTrainName, actualTrainCount, trainCount);

const trainSchedule = formatTrainSchedulePayload(
validTrainConfig,
trainName,
newStartTimeString
);
const trainSchedule = formatTrainSchedulePayload(validTrainConfig, trainName, newStartTime);
trainScheduleParams.push({ ...trainSchedule });
actualTrainCount += trainStep;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import ChipsSNCF from 'common/BootstrapSNCF/ChipsSNCF';
import InputSNCF from 'common/BootstrapSNCF/InputSNCF';
import { useOsrdConfActions, useOsrdConfSelectors } from 'common/osrdContext';
import { useAppDispatch } from 'store';
import { dateTimeToIso } from 'utils/date';
import { parseLocalDateTime, formatLocalDateTime } from 'utils/date';
import { useDebounce } from 'utils/helpers';
import { isInvalidFloatNumber } from 'utils/numbers';

Expand All @@ -27,7 +27,7 @@ export default function TrainSettings() {
const startTimeFromStore = useSelector(getStartTime);

const [name, setName] = useState<string>(nameFromStore);
const [startTime, setStartTime] = useState(startTimeFromStore.substring(0, 19));
const [startTime, setStartTime] = useState(formatLocalDateTime(startTimeFromStore));
const [initialSpeed, setInitialSpeed] = useState<number | undefined>(initialSpeedFromStore);
const dispatch = useAppDispatch();

Expand All @@ -52,8 +52,8 @@ export default function TrainSettings() {
}, [debouncedName]);

useEffect(() => {
const formatedStartTime = dateTimeToIso(debouncedStartTime);
if (formatedStartTime) dispatch(updateStartTime(formatedStartTime));
const newStartTime = parseLocalDateTime(debouncedStartTime);
if (newStartTime) dispatch(updateStartTime(newStartTime));
}, [debouncedStartTime]);

useEffect(() => {
Expand All @@ -63,7 +63,7 @@ export default function TrainSettings() {
useEffect(() => {
setName(nameFromStore);
setInitialSpeed(initialSpeedFromStore);
setStartTime(startTimeFromStore.substring(0, 19));
setStartTime(formatLocalDateTime(startTimeFromStore));
}, [nameFromStore, initialSpeedFromStore, startTimeFromStore]);

const isInvalidTrainScheduleName = isInvalidName(name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ const checkCurrentConfig = (
margins: formatMargin(compact(pathSteps)),
schedule: formatSchedule(compact(pathSteps)),
powerRestrictions: powerRestriction,
firstStartTime: startTime,
firstStartTime: startTime.toISOString(),
speedLimitByTag,
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ValidConfig } from '../types';
export default function formatTrainSchedulePayload(
validConfig: ValidConfig,
trainName: string,
startTime: string
startTime: Date
): TrainScheduleBase {
const {
constraintDistribution,
Expand Down Expand Up @@ -35,7 +35,7 @@ export default function formatTrainSchedulePayload(
rolling_stock_name: rollingStockName,
schedule: validConfig.schedule,
speed_limit_tag: speedLimitByTag,
start_time: startTime,
start_time: startTime.toISOString(),
train_name: trainName,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type SimulationSummaryResultSuccess = Extract<SimulationSummaryResult, { status:

export type TrainScheduleWithDetails = Omit<
TrainScheduleResult,
'train_name' | 'rolling_stock_name' | 'timetable_id'
'train_name' | 'rolling_stock_name' | 'timetable_id' | 'start_time'
> & {
id: number;
trainName: string;
Expand Down
12 changes: 10 additions & 2 deletions front/src/reducers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const saveUserFilter = createFilter('user', userWhiteList);
const saveMainFilter = createFilter('main', mainWhiteList);

// Deserialize date strings coming from local storage
const dateTransform = createTransform(
const stdcmPathStepsDateTransform = createTransform(
null,
(outboundState: { arrival?: string }[]) =>
outboundState.map(({ arrival, ...step }) => {
Expand All @@ -69,14 +69,22 @@ const dateTransform = createTransform(
}),
{ whitelist: ['stdcmPathSteps'] }
);
const operationalStudiesDateTransform = createTransform(
null,
({ startTime, ...outboundState }: { startTime: string }) => ({
...outboundState,
startTime: new Date(startTime),
}),
{ whitelist: ['operationalStudiesConf'] }
);

// Useful to only blacklist a sub-propertie of osrdconf
const buildOsrdConfPersistConfig = <T extends OsrdConfState>(
slice: ConfSlice
): PersistConfig<T> => ({
key: slice.name,
storage,
transforms: [dateTransform],
transforms: [stdcmPathStepsDateTransform, operationalStudiesDateTransform],
blacklist: ['featureInfoClick'],
});

Expand Down
5 changes: 2 additions & 3 deletions front/src/reducers/osrdconf/operationalStudiesConf/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { TrainScheduleWithDetails } from 'modules/trainschedule/components/
import computeBasePathStep from 'modules/trainschedule/helpers/computeBasePathStep';
import { defaultCommonConf, buildCommonConfReducers } from 'reducers/osrdconf/osrdConfCommon';
import type { OsrdConfState } from 'reducers/osrdconf/types';
import { convertIsoUtcToLocalTime } from 'utils/date';
import { msToKmh } from 'utils/physics';

import { builPowerRestrictionReducer } from './powerRestrictionReducer';
Expand All @@ -27,7 +26,7 @@ export const operationalStudiesConfSlice = createSlice({
rollingStock,
trainName,
initial_speed,
start_time,
startTime,
options,
speedLimitTag,
labels,
Expand All @@ -38,7 +37,7 @@ export const operationalStudiesConfSlice = createSlice({

state.rollingStockID = rollingStock?.id;
state.pathSteps = path.map((_, index) => computeBasePathStep(action.payload, index));
state.startTime = convertIsoUtcToLocalTime(start_time);
state.startTime = startTime;

state.name = trainName;
state.initialSpeed = initial_speed ? Math.floor(msToKmh(initial_speed) * 10) / 10 : 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ describe('simulationConfReducer', () => {
id: 1,
trainName: 'train1',
constraint_distribution: 'MARECO',
start_time: '2021-01-01T00:00:00Z',
rollingStock: { id: 1, name: 'rollingStock1' } as LightRollingStockWithLiveries,
path: [
{ id: 'id1', uic: 123 },
Expand Down Expand Up @@ -88,7 +87,7 @@ describe('simulationConfReducer', () => {
receptionSignal: undefined,
},
],
startTime: '2021-01-01T00:00:00+00:00',
startTime: new Date('2021-01-01T00:00:00+00:00'),
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ const testCommonConfReducers = (slice: OperationalStudiesConfSlice | StdcmConfSl
});

it('should handle updateStartTime', () => {
const newStartTime = '2024-05-01T11:08:00.000+01:00';
const newStartTime = new Date('2024-05-01T11:08:00.000+01:00');
defaultStore.dispatch(slice.actions.updateStartTime(newStartTime));
const state = defaultStore.getState()[slice.name];
expect(state.startTime).toBe(newStartTime);
Expand Down
2 changes: 1 addition & 1 deletion front/src/reducers/osrdconf/osrdConfCommon/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const defaultCommonConf: OsrdConfState = {
// Corresponds to origin and destination not defined
pathSteps: [null, null],
rollingStockComfort: 'STANDARD' as const,
startTime: new Date().toISOString(),
startTime: new Date(),
};

interface CommonConfReducers<S extends OsrdConfState> extends InfraStateReducers<S> {
Expand Down
3 changes: 1 addition & 2 deletions front/src/reducers/osrdconf/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ export interface OsrdConfState extends InfraState {
featureInfoClick: { displayPopup: boolean; feature?: Feature; coordinates?: number[] };
pathSteps: (PathStep | null)[];
rollingStockComfort: Comfort;
// Format ISO 8601
startTime: string;
startTime: Date;
}

export interface StandardAllowance {
Expand Down
30 changes: 15 additions & 15 deletions front/src/utils/__tests__/date.spec.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
import { describe, it, expect } from 'vitest';

import {
dateTimeToIso,
parseLocalDateTime,
isoDateToMs,
formatToIsoDate,
serializeDateTimeWithoutYear,
extractDateAndTimefromISO,
extractDateAndTime,
isArrivalDateInSearchTimeWindow,
} from 'utils/date';

describe('dateTimeToIso', () => {
describe('parseLocalDateTime', () => {
it('should return an iso date by passing a date without milliseconds', () => {
const inputDate = '2024-04-25T08:20';
const isoDate = dateTimeToIso(inputDate);
expect(isoDate).toEqual('2024-04-25T08:20:00Z'); // Ends by Z because CI seems to be in UTC timezone
const isoDate = parseLocalDateTime(inputDate);
expect(isoDate?.toISOString()).toEqual('2024-04-25T08:20:00.000Z');
});

it('should return an iso date by passing a date with milliseconds', () => {
const inputDate = '2024-04-25T08:20:10';
const isoDate = dateTimeToIso(inputDate);
expect(isoDate).toEqual('2024-04-25T08:20:10Z'); // Ends by Z because CI seems to be in UTC timezone
const isoDate = parseLocalDateTime(inputDate);
expect(isoDate?.toISOString()).toEqual('2024-04-25T08:20:10.000Z');
});

it('should return an iso date by passing a date with a space between date and time instead of a T', () => {
const inputDate = '2024-04-25 08:20:10';
const isoDate = dateTimeToIso(inputDate);
expect(isoDate).toEqual('2024-04-25T08:20:10Z'); // Ends by Z because CI seems to be in UTC timezone
const isoDate = parseLocalDateTime(inputDate);
expect(isoDate?.toISOString()).toEqual('2024-04-25T08:20:10.000Z');
});

it('should return null by passing a date with the wrong format', () => {
const inputDate = '04-25 08:20:10';
const isoDate = dateTimeToIso(inputDate);
const isoDate = parseLocalDateTime(inputDate);
expect(isoDate).toBeNull();
});
});
Expand Down Expand Up @@ -65,10 +65,10 @@ describe('serializeDateTimeWithoutYear', () => {
});
});

describe('extractDateAndTimefromISO', () => {
describe('extractDateAndTime', () => {
it('should correctly parse the date and time from an ISO string', () => {
const arrivalTime = '2024-10-05T14:30:00+00:00';
const result = extractDateAndTimefromISO(arrivalTime);
const arrivalTime = new Date('2024-10-05T14:30:00+00:00');
const result = extractDateAndTime(arrivalTime);

expect(result).toEqual({
arrivalDate: '2024-10-05',
Expand All @@ -79,8 +79,8 @@ describe('extractDateAndTimefromISO', () => {
});

it('should handle single digit hours and minutes correctly', () => {
const arrivalTime = '2024-10-05T09:05:00+00:00';
const result = extractDateAndTimefromISO(arrivalTime);
const arrivalTime = new Date('2024-10-05T09:05:00+00:00');
const result = extractDateAndTime(arrivalTime);

expect(result).toEqual({
arrivalDate: '2024-10-05',
Expand Down
Loading
Loading