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: add track column to timestops table #9614

Merged
merged 4 commits into from
Nov 28, 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
1 change: 1 addition & 0 deletions front/public/locales/en/timesStops.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@
"theoreticalMargin": "theoretical margin",
"theoreticalMarginPlaceholder": "% or min/100km",
"theoreticalMarginSeconds": "theoretical margin (s)",
"trackName": "track",
"waypoint": "Waypoint {{id}}"
}
1 change: 1 addition & 0 deletions front/public/locales/fr/timesStops.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@
"theoreticalMargin": "marge théorique",
"theoreticalMarginPlaceholder": "% ou min/100km",
"theoreticalMarginSeconds": "marge théorique (s)",
"trackName": "voie",
"waypoint": "Via {{id}}"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useRef, useCallback } from 'react';

import { uniq } from 'lodash';

import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import type { TrackSection } from 'common/api/osrdEditoastApi';

export default function useCachedTrackSections(infraId: number) {
const trackIdsRef = useRef<Set<string>>(new Set());
const trackSectionsRef = useRef<Record<string, TrackSection>>({});
const [loadInfraObject, { isLoading }] =
osrdEditoastApi.endpoints.postInfraByInfraIdObjectsAndObjectType.useMutation();

const getTrackSectionsByIds = useCallback(
async (requestedTrackIds: string[]) => {
const uniqueNewIds = uniq(requestedTrackIds.filter((id) => !trackIdsRef.current.has(id)));
if (uniqueNewIds.length !== 0) {
try {
const fetchedSections = await loadInfraObject({
infraId,
objectType: 'TrackSection',
body: uniqueNewIds,
}).unwrap();

uniqueNewIds.forEach((id) => trackIdsRef.current.add(id));
fetchedSections.forEach((rawSection) => {
const trackSection = rawSection.railjson as TrackSection;
trackSectionsRef.current[trackSection.id] = trackSection;
});
} catch (error) {
console.error('Failed to fetch track sections:', error);
}
}

return trackSectionsRef.current;
},
[infraId]
);

return { getTrackSectionsByIds, isLoading };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createContext, useContext, useMemo, type ReactNode } from 'react';

import useCachedTrackSections from 'applications/operationalStudies/hooks/useCachedTrackSections';
import type { TrackSection } from 'common/api/osrdEditoastApi';

type ScenarioContextType = {
getTrackSectionsByIds: (requestedTrackIds: string[]) => Promise<Record<string, TrackSection>>;
infraId: number;
trackSectionsLoading: boolean;
} | null;
const ScenarioContext = createContext<ScenarioContextType>(null);

type ScenarioContextProviderProps = { infraId: number; children: ReactNode };

export const ScenarioContextProvider = ({ infraId, children }: ScenarioContextProviderProps) => {
const { getTrackSectionsByIds, isLoading: trackSectionsLoading } =
useCachedTrackSections(infraId);
const providedContext = useMemo(
() => ({
getTrackSectionsByIds,
infraId,
trackSectionsLoading,
}),
[getTrackSectionsByIds, infraId, trackSectionsLoading]
);
return <ScenarioContext.Provider value={providedContext}>{children}</ScenarioContext.Provider>;
};

export const useScenarioContext = () => {
const context = useContext(ScenarioContext);
if (!context) {
throw new Error('useScenarioContext must be used within a ScenarioContextProvider');
}
return context;
};
clarani marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useEffect } from 'react';

import { type Position } from '@turf/helpers';
import { omit } from 'lodash';
import { useSelector } from 'react-redux';

import {
osrdEditoastApi,
Expand All @@ -13,7 +12,7 @@ import {
type TrainScheduleResult,
type PathfindingResult,
} from 'common/api/osrdEditoastApi';
import { useOsrdConfActions, useOsrdConfSelectors } from 'common/osrdContext';
import { useOsrdConfActions } from 'common/osrdContext';
import {
formatSuggestedOperationalPoints,
matchPathStepAndOp,
Expand All @@ -29,6 +28,7 @@ import { castErrorToFailure } from 'utils/error';
import { getPointCoordinates } from 'utils/geometry';

import type { ManageTrainSchedulePathProperties } from '../types';
import { useScenarioContext } from './useScenarioContext';

type ItineraryForTrainUpdate = {
pathSteps: (PathStep | null)[];
Expand Down Expand Up @@ -64,8 +64,6 @@ const useSetupItineraryForTrainUpdate = (
setPathProperties: (pathProperties: ManageTrainSchedulePathProperties) => void,
trainIdToEdit: number
) => {
const { getInfraID } = useOsrdConfSelectors();
const infraId = useSelector(getInfraID);
const dispatch = useAppDispatch();

const { updatePathSteps } = useOsrdConfActions();
Expand All @@ -77,6 +75,7 @@ const useSetupItineraryForTrainUpdate = (
osrdEditoastApi.endpoints.postInfraByInfraIdPathfindingBlocks.useMutation();
const [postPathProperties] =
osrdEditoastApi.endpoints.postInfraByInfraIdPathProperties.useMutation();
const { infraId } = useScenarioContext();

useEffect(() => {
const computeItineraryForTrainUpdate = async (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import BreadCrumbs from 'applications/operationalStudies/components/BreadCrumbs';
import ScenarioContent from 'applications/operationalStudies/components/Scenario/ScenarioContent';
import useScenario from 'applications/operationalStudies/hooks/useScenario';
import { ScenarioContextProvider } from 'applications/operationalStudies/hooks/useScenarioContext';
import useScenarioQueryParams from 'applications/operationalStudies/hooks/useScenarioQueryParams';
import NavBarSNCF from 'common/BootstrapSNCF/NavBarSNCF';
import useInfraStatus from 'modules/pathfinding/hooks/useInfraStatus';
Expand All @@ -17,7 +18,7 @@ const Scenario = () => {
if (!scenario || !timetable || !infra) return null;

return (
<>
<ScenarioContextProvider infraId={infra.id}>
<NavBarSNCF
appName={
<BreadCrumbs project={scenario.project} study={scenario.study} scenario={scenario} />
Expand All @@ -29,7 +30,7 @@ const Scenario = () => {
infra={infra}
infraMetadata={infraData}
/>
</>
</ScenarioContextProvider>
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ const SimulationResults = ({
const { operationalPoints, loading: formattedOpPointsLoading } = useFormattedOperationalPoints(
selectedTrainSchedule,
trainSimulation,
pathProperties,
infraId
pathProperties
);

// Compute path items coordinates in order to place them on the map
Expand Down
5 changes: 3 additions & 2 deletions front/src/modules/pathfinding/hooks/usePathfinding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { compact, isEqual, isObject } from 'lodash';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';

import { useScenarioContext } from 'applications/operationalStudies/hooks/useScenarioContext';
import type { ManageTrainSchedulePathProperties } from 'applications/operationalStudies/types';
import type {
PathfindingInputError,
Expand Down Expand Up @@ -150,9 +151,8 @@ export const usePathfinding = (
) => {
const { t } = useTranslation(['operationalStudies/manageTrainSchedule']);
const dispatch = useAppDispatch();
const { getInfraID, getOrigin, getDestination, getVias, getPathSteps, getPowerRestriction } =
const { getOrigin, getDestination, getVias, getPathSteps, getPowerRestriction } =
useOsrdConfSelectors();
const infraId = useSelector(getInfraID, isEqual);
const origin = useSelector(getOrigin, isEqual);
const destination = useSelector(getDestination, isEqual);
const vias = useSelector(getVias(), isEqual);
Expand All @@ -178,6 +178,7 @@ export const usePathfinding = (
osrdEditoastApi.endpoints.postInfraByInfraIdPathProperties.useMutation();

const { updatePathSteps } = useOsrdConfActions();
const { infraId } = useScenarioContext();

const generatePathfindingParams = (): PostInfraByInfraIdPathfindingBlocksApiArg | null => {
setPathProperties?.(undefined);
Expand Down
10 changes: 7 additions & 3 deletions front/src/modules/pathfinding/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import getStepLocation from './helpers/getStepLocation';

export const formatSuggestedOperationalPoints = (
operationalPoints: NonNullable<Required<PathProperties['operational_points']>>,
geometry: GeoJsonLineString,
pathLength: number
geometry?: GeoJsonLineString,
pathLength?: number
): SuggestedOP[] =>
operationalPoints.map((op) => ({
opId: op.id,
Expand All @@ -33,7 +33,11 @@ export const formatSuggestedOperationalPoints = (
offsetOnTrack: op.part.position,
track: op.part.track,
positionOnPath: op.position,
coordinates: getPointCoordinates(geometry, pathLength, op.position),
coordinates:
(geometry !== undefined &&
pathLength !== undefined &&
getPointCoordinates(geometry, pathLength, op.position)) ||
undefined,
}));

export const matchPathStepAndOp = (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import * as d3 from 'd3';
import { uniq } from 'lodash';

import type { TrackSectionEntity } from 'applications/editor/tools/trackEdition/types';
import type {
OperationalPointWithTimeAndSpeed,
PathPropertiesFormatted,
SimulationResponseSuccess,
} from 'applications/operationalStudies/types';
import { convertDepartureTimeIntoSec } from 'applications/operationalStudies/utils';
import {
osrdEditoastApi,
type ReportTrain,
type TrackSection,
type TrainScheduleBase,
} from 'common/api/osrdEditoastApi';
import type { SpeedRanges } from 'reducers/simulationResults/types';
import { store } from 'store';
import { mmToM, msToKmhRounded } from 'utils/physics';
import { ISO8601Duration2sec, ms2sec } from 'utils/timeManipulation';

Expand Down Expand Up @@ -108,20 +104,8 @@ export const formatOperationalPoints = async (
operationalPoints: PathPropertiesFormatted['operationalPoints'],
simulatedTrain: SimulationResponseSuccess,
train: TrainScheduleBase,
infraId: number
trackSections: Record<string, TrackSection>
): Promise<OperationalPointWithTimeAndSpeed[]> => {
// Get operational points metadata
const trackIds = uniq(operationalPoints.map((op) => op.part.track));
const trackSections = await store
.dispatch(
osrdEditoastApi.endpoints.postInfraByInfraIdObjectsAndObjectType.initiate({
infraId,
objectType: 'TrackSection',
body: trackIds,
})
)
.unwrap();

// Format operational points
const formattedStops: OperationalPointWithTimeAndSpeed[] = [];

Expand All @@ -147,14 +131,11 @@ export const formatOperationalPoints = async (
}
}

const associatedTrackSection = trackSections.find(
(trackSection) => (trackSection.railjson as TrackSection).id === op.part.track
);
const associatedTrackSection = trackSections[op.part.track];

let metadata;
if (associatedTrackSection) {
metadata = (associatedTrackSection.railjson as TrackSectionEntity['properties']).extensions
?.sncf;
metadata = associatedTrackSection.extensions?.sncf;
}

const opCommonProp = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable import/prefer-default-export */
import { useEffect, useState } from 'react';

import { useScenarioContext } from 'applications/operationalStudies/hooks/useScenarioContext';
import type {
OperationalPointWithTimeAndSpeed,
PathPropertiesFormatted,
Expand All @@ -16,28 +17,31 @@ import { formatOperationalPoints } from '../SimulationResultExport/utils';
export const useFormattedOperationalPoints = (
train?: TrainScheduleBase,
simulatedTrain?: SimulationResponseSuccess,
pathProperties?: PathPropertiesFormatted,
infraId?: number
pathProperties?: PathPropertiesFormatted
) => {
const [operationalPoints, setOperationalPoints] = useState<OperationalPointWithTimeAndSpeed[]>();
const [loading, setLoading] = useState(false);
const { getTrackSectionsByIds } = useScenarioContext();

useEffect(() => {
if (train && simulatedTrain && pathProperties && infraId) {
if (train && simulatedTrain && pathProperties) {
const fetchOperationalPoints = async () => {
setLoading(true);

const trackIds = pathProperties.operationalPoints.map((op) => op.part.track);
const trackSections = await getTrackSectionsByIds(trackIds);
const formattedOperationalPoints = await formatOperationalPoints(
pathProperties.operationalPoints,
simulatedTrain,
train,
infraId
trackSections
);
setOperationalPoints(formattedOperationalPoints);
setLoading(false);
};
fetchOperationalPoints();
}
}, [train, simulatedTrain, pathProperties, infraId]);
}, [train, simulatedTrain, pathProperties, getTrackSectionsByIds]);

return { operationalPoints, loading };
};
12 changes: 12 additions & 0 deletions front/src/modules/timesStops/TimesStops.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { DynamicDataSheetGrid, type DataSheetGridProps } from 'react-datasheet-g
import type { Operation } from 'react-datasheet-grid/dist/types';
import { useTranslation } from 'react-i18next';

import { Loader } from 'common/Loaders/Loader';

import { useTimeStopsColumns } from './hooks/useTimeStopsColumns';
import { type TableType, type TimeStopsRow } from './types';

Expand All @@ -13,6 +15,7 @@ type TimesStopsProps<T extends TimeStopsRow> = {
stickyRightColumn?: DataSheetGridProps['stickyRightColumn'];
headerRowHeight?: number;
onChange?: (newRows: T[], operation: Operation) => void;
dataIsLoading: boolean;
};

const TimesStops = <T extends TimeStopsRow>({
Expand All @@ -22,11 +25,20 @@ const TimesStops = <T extends TimeStopsRow>({
stickyRightColumn,
headerRowHeight,
onChange,
dataIsLoading,
}: TimesStopsProps<T>) => {
const { t } = useTranslation('timesStops');

const columns = useTimeStopsColumns(tableType, rows);

if (dataIsLoading) {
return (
<div style={{ height: '600px' }}>
<Loader />
</div>
);
}

if (!rows) {
return (
<div className="d-flex justify-content-center align-items-center h-100">
Expand Down
Loading
Loading