Skip to content

Commit

Permalink
clean code clara
Browse files Browse the repository at this point in the history
  • Loading branch information
clarani committed Jul 5, 2024
1 parent b032b9a commit 9abcaa4
Show file tree
Hide file tree
Showing 41 changed files with 1,275 additions and 1,187 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,11 @@
"electrification": "Electrification",
"inconsistent_one": "The interval below has inconsistencies. The default speed effort curve will be used for this.",
"inconsistent_other": "The intervals below contain inconsistencies. The default speed effort curves will be used for these.",
"powerRestrictionInvalidCombination": "- {{powerRestrictionCode}} is incompatible with electrification {{electrification}} of the path between {{begin}}m and {{end}}m",
"marginsAndPowerRestrictionsReset": "Margins and power restrictions have been reset.",
"missingPowerRestriction": "- Missing power restriction between {{begin}}m and {{end}}m.",
"modeNotHandled": "- No power restriction should be given between {{begin}}m and {{end}}m since the electrification mode {{electrification}} is not handled.",
"pathfindingChange": "Pathfinding changed",
"marginsAndPowerRestrictionsReset": "Margins and power restrictions have been reset."
"powerRestrictionInvalidCombination": "- {{powerRestrictionCode}} is incompatible with electrification {{electrification}} of the path between {{begin}}m and {{end}}m",
"powerRestrictionsReset": "Power restrictions have been reset."
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,11 @@
"electrification": "Électrification",
"inconsistent_one": "Un intervalle comporte des incohérences. La courbe effort vitesse par défaut sera utilisée pour celui-ci.",
"inconsistent_other": "Plusieurs intervalles comportent des incohérences. Les courbes effort vitesse par défaut seront utilisées pour ceux-ci.",
"powerRestrictionInvalidCombination": "- Code {{powerRestrictionCode}} incompatible avec l'électrification à {{electrification}} de l'itinéraire entre {{begin}}m et {{end}}m. ",
"marginsAndPowerRestrictionsReset": "Les marges et les restrictions de puissance ont été réinitialisées.",
"missingPowerRestriction": "- Restriction de puissance manquante entre {{begin}}m et {{end}}m.",
"modeNotHandled": "- Aucune restriction de puissance ne devrait être renseignée entre {{begin}}m and {{end}}m comme le matériel roulant ne supporte pas l'électrification {{electrification}}.",
"pathfindingChange": "Changement de chemin",
"marginsAndPowerRestrictionsReset": "Les marges et les restrictions de puissance ont été réinitialisées."
"powerRestrictionInvalidCombination": "- Code {{powerRestrictionCode}} incompatible avec l'électrification à {{electrification}} de l'itinéraire entre {{begin}}m et {{end}}m.",
"powerRestrictionsReset": "Les restrictions de puissance ont été réinitialisées."
}
}
13 changes: 7 additions & 6 deletions front/src/applications/operationalStudies/consts.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import type { Position } from 'geojson';

import type { ElectrificationRange, ElectrificationUsage } from 'common/api/osrdEditoastApi';
import type {
ElectrificationRange,
ElectrificationUsage,
TrainScheduleBase,
} from 'common/api/osrdEditoastApi';
import type { LinearMetadataItem } from 'common/IntervalsDataViz/types';
import i18n from 'i18n';
import type { Mode } from 'modules/simulationResult/components/SpeedSpaceChart/types';
import type { HeightPosition } from 'reducers/osrdsimulation/types';
import type { ArrayElement } from 'utils/types';

export const BLOCKTYPES = [
{
Expand Down Expand Up @@ -125,11 +130,7 @@ export type StudyType = typeof STUDY_TYPES;

export type PowerRestrictionRange = LinearMetadataItem<{ value: string }>;

export type PowerRestrictionV2 = {
from: string;
to: string;
code: string;
};
export type PowerRestrictionV2 = ArrayElement<TrainScheduleBase['power_restrictions']>;

// electrical profiles
interface Profile {
Expand Down
7 changes: 4 additions & 3 deletions front/src/applications/operationalStudies/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
PathResponse,
PathfindingResult,
ProjectPathTrainResult,
RangedValue,
SimulationResponse,
} from 'common/api/osrdEditoastApi';
import type { SuggestedOP } from 'modules/trainschedule/components/ManageTrainSchedule/types';
Expand Down Expand Up @@ -108,6 +109,7 @@ export type PositionData<T extends 'gradient' | 'radius'> = {
position: number;
};

/** Start and stop are in meters */
export type ElectrificationRangeV2 = {
electrificationUsage: ElectrificationUsageV2;
start: number;
Expand Down Expand Up @@ -145,15 +147,14 @@ export type ElectricalProfileValue = Extract<
{ status: 'success' }
>['electrical_profiles']['values'][number];

/**
* Electrifications start and stop are in meters
*/
/** Electrifications start and stop are in meters */
export type PathPropertiesFormatted = {
electrifications: ElectrificationRangeV2[];
curves: PositionData<'radius'>[];
slopes: PositionData<'gradient'>[];
operationalPoints: NonNullable<PathProperties['operational_points']>;
geometry: NonNullable<PathProperties['geometry']>;
voltages: RangedValue[];
};

export type SimulationResponseSuccess = Extract<SimulationResponse, { status: 'success' }>;
Expand Down
21 changes: 8 additions & 13 deletions front/src/applications/operationalStudies/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { omit } from 'lodash';

import type {
PathProperties,
ProjectPathTrainResult,
RangedValue,
} from 'common/api/osrdEditoastApi';
import type { PathProperties, ProjectPathTrainResult } from 'common/api/osrdEditoastApi';
import getPathVoltages from 'modules/pathfinding/helpers/getPathVoltages';
import { convertUTCDateToLocalDate, isoDateToMs } from 'utils/date';
import { mmToM } from 'utils/physics';
import { ms2sec } from 'utils/timeManipulation';
Expand Down Expand Up @@ -86,14 +83,6 @@ export const transformBoundariesDataToRangesData = <
return formatedData;
};

export const addRange = (ranges: RangedValue[], begin: number, end: number, value: string) => {
ranges.push({
begin,
end,
value,
});
};

export const formatElectrificationRanges = (
electrifications: ElectricalRangesData<ElectrificationValue>[],
electricalProfiles: ElectricalRangesData<ElectricalProfileValue>[]
Expand Down Expand Up @@ -191,12 +180,18 @@ export const preparePathPropertiesData = (
electricalProfilesRanges
);

const voltageRanges = getPathVoltages(
electrifications as NonNullable<PathProperties['electrifications']>,
pathLength
);

return {
electrifications: electrificationRanges,
curves: formattedCurves,
slopes: formattedSlopes,
operationalPoints: operational_points as NonNullable<PathProperties['operational_points']>,
geometry: geometry as NonNullable<PathProperties['geometry']>,
voltages: voltageRanges,
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,16 @@ import { compact } from 'lodash';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';

import type {
ElectrificationVoltage,
ManageTrainSchedulePathProperties,
} from 'applications/operationalStudies/types';
import { addRange } from 'applications/operationalStudies/utils';
import type { ManageTrainSchedulePathProperties } from 'applications/operationalStudies/types';
import allowancesPic from 'assets/pictures/components/allowances.svg';
import pahtFindingPic from 'assets/pictures/components/pathfinding.svg';
import simulationSettings from 'assets/pictures/components/simulationSettings.svg';
import rollingStockPic from 'assets/pictures/components/train.svg';
import type { IntervalItem } from 'common/IntervalsEditor/types';
import { useOsrdConfSelectors } from 'common/osrdContext';
import { useStoreDataForSpeedLimitByTagSelector } from 'common/SpeedLimitByTagSelector/useStoreDataForSpeedLimitByTagSelector';
import Tabs from 'common/Tabs';
import ItineraryV2 from 'modules/pathfinding/components/Itinerary/ItineraryV2';
import getPathVoltages from 'modules/pathfinding/helpers/getPathVoltages';
import { upsertViasInOPs } from 'modules/pathfinding/utils';
import PowerRestrictionsSelectorV2 from 'modules/powerRestriction/components/PowerRestrictionsSelectorV2';
import RollingStock2Img from 'modules/rollingStock/components/RollingStock2Img';
Expand All @@ -29,8 +25,6 @@ import { Map } from 'modules/trainschedule/components/ManageTrainSchedule';
import SimulationSettings from 'modules/trainschedule/components/ManageTrainSchedule/SimulationSettings';
import TrainSettings from 'modules/trainschedule/components/ManageTrainSchedule/TrainSettings';
import { formatKmValue } from 'utils/strings';
import { upsertViasInOPs } from 'modules/pathfinding/utils';
import { compact } from 'lodash';

const ManageTrainScheduleV2 = () => {
const { t } = useTranslation(['operationalStudies/manageTrainSchedule']);
Expand Down Expand Up @@ -61,67 +55,12 @@ const ManageTrainScheduleV2 = () => {
allWaypoints,
});
}
}, [])

const [initialPowerRestrictions, setInitialPowerRestrictions] = useState<RangedValueV2[]>([]);

const isElectrification = (
value: ElectrificationVoltage
): value is { type: 'electrification'; voltage: string } => value.type === 'electrification';
}, []);

type RangedValueV2 = {
begin: number;
end: number;
value: string;
};

useEffect(() => {
if (pathProperties) {
const allVias = upsertViasInOPs(
pathProperties.suggestedOperationalPoints,
compact(pathSteps)
);
setPathProperties({
...pathProperties,
allVias,
});
}
}, [pathSteps]);

const pathElectrificationRanges = (): IntervalItem[] => {
if (!pathProperties || !pathProperties.electrifications) return [];

const boundaries = [0, ...pathProperties.electrifications.boundaries, pathProperties.length];
const values = [...pathProperties.electrifications.values];

const ranges: RangedValueV2[] = [];
let start = boundaries[0];
let currentVoltage = isElectrification(values[0]) ? values[0].voltage : '';

for (let i = 1; i < values.length; i += 1) {
const currentValue = values[i];
if (isElectrification(currentValue) && currentValue.voltage !== currentVoltage) {
addRange(ranges, start, boundaries[i], currentVoltage);
start = boundaries[i];
currentVoltage = currentValue.voltage;
}
}

// Add the last segment
addRange(ranges, start, boundaries[boundaries.length - 1], currentVoltage);
setInitialPowerRestrictions(ranges);
return ranges;
};

useMemo(() => {
if (!pathProperties) return [];

return pathElectrificationRanges().map((electrificationRange) => ({
begin: electrificationRange.begin,
end: electrificationRange.end,
value: `${electrificationRange.value}`,
}));
}, [pathProperties]);
const voltageRanges = useMemo(
() => getPathVoltages(pathProperties?.electrifications, pathProperties?.length),
[pathProperties]
);

const tabRollingStock = {
id: 'rollingstock',
Expand Down Expand Up @@ -211,11 +150,11 @@ const ManageTrainScheduleV2 = () => {
dispatchUpdateSpeedLimitByTag={dispatchUpdateSpeedLimitByTag}
constraintDistribution={constraintDistribution}
/>
{rollingStock && isElectric(rollingStock.effort_curves.modes) && (
{rollingStock && isElectric(rollingStock.effort_curves.modes) && pathProperties && (
<PowerRestrictionsSelectorV2
rollingStockModes={rollingStock.effort_curves.modes}
rollingStockPowerRestrictions={rollingStock.power_restrictions}
pathElectrificationRanges={initialPowerRestrictions}
voltageRanges={voltageRanges}
pathProperties={pathProperties}
/>
)}
Expand Down
4 changes: 2 additions & 2 deletions front/src/applications/stdcmV2/components/StdcmVias.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const StdcmVias = ({ disabled = false, setCurrentSimulationInputs }: StdcmConfig

const updatePathStepsList = (pathStep: PathStep | null, index: number) => {
const newPathSteps = replaceElementAtIndex(pathSteps, index, pathStep);
dispatch(updatePathSteps(newPathSteps));
dispatch(updatePathSteps({ pathSteps: newPathSteps }));
};

const updatePathStepStopTime = (stopTime: string, index: number) => {
Expand Down Expand Up @@ -95,7 +95,7 @@ const StdcmVias = ({ disabled = false, setCurrentSimulationInputs }: StdcmConfig
Icon={<Location size="lg" variant="base" />}
onClick={() => {
const newPathSteps = addElementAtIndex(pathSteps, pathSteps.length - 1, null);
dispatch(updatePathSteps(newPathSteps));
dispatch(updatePathSteps({ pathSteps: newPathSteps }));
}}
/>
</div>
Expand Down
5 changes: 2 additions & 3 deletions front/src/common/IntervalsEditor/IntervalsEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
import { createEmptySegmentAt, removeSegment } from './utils';
import ZoomButtons from './ZoomButtons';

type IntervalsEditorProps = {
export type IntervalsEditorProps = {
/** Additionnal read-only data that will be displayed along the path, below the intervals editor */
additionalData?: AdditionalDataItem[];
/** Default value used when a new range is created */
Expand All @@ -54,9 +54,8 @@ type IntervalsEditorProps = {
disableDrag?: boolean;
onResizeFromInput?: (
intervalIndex: number,
newEnd: number,
context: 'begin' | 'end',
newBegin: number
newPosition: number
) => void;
} & (
| {
Expand Down
15 changes: 3 additions & 12 deletions front/src/common/IntervalsEditor/IntervalsEditorCommonForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,15 @@ import DebouncedNumberInputSNCF from 'common/BootstrapSNCF/FormSNCF/DebouncedNum
import { fixLinearMetadataItems, resizeSegment } from 'common/IntervalsDataViz/data';
import { notEmpty } from 'common/IntervalsDataViz/utils';

import type { IntervalsEditorProps } from './IntervalsEditor';
import type { IntervalItem } from './types';

type IntervalsEditorFormProps = {
data: IntervalItem[];
interval: IntervalItem;
selectedIntervalIndex: number;
setData: (newData: IntervalItem[], selectedIntervalIndex?: number) => void;
onInputChange?: (
intervalIndex: number,
newEnd: number,
context: 'begin' | 'end',
newBegin: number
) => void;
onInputChange?: IntervalsEditorProps['onResizeFromInput'];
setSelectedIntervalIndex: (selectedIntervalIndex: number) => void;
totalLength: number;
defaultValue: string | number;
Expand Down Expand Up @@ -62,12 +58,7 @@ const IntervalsEditorCommonForm = ({
defaultValue,
});
if (onInputChange) {
onInputChange(
selectedIntervalIndex,
context === 'end' ? newPosition : interval.end,
context,
context === 'begin' ? newPosition : interval.begin
); // Pass newBegin when context is 'begin'
onInputChange(selectedIntervalIndex, context, newPosition); // Pass newBegin when context is 'begin'
} else {
setData(fixedResults, selectedIntervalIndex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ const ItineraryV2 = ({

const inverseOD = () => {
const revertedPathSteps = [...pathSteps].reverse();
dispatch(updatePathSteps(revertedPathSteps));
dispatch(updatePathSteps({ pathSteps: revertedPathSteps, resetPowerRestrictions: true }));
};

const resetPathfinding = () => {
setPathProperties(undefined);
dispatch(updatePathSteps([null, null]));
dispatch(updatePathSteps({ pathSteps: [null, null], resetPowerRestrictions: true }));
};

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ const ModalSuggestedVias = ({ suggestedVias }: ModalSuggestedViasProps) => {
const removeViaFromPath = (op: SuggestedOP) => {
const updatedPathSteps = [...pathSteps];
dispatch(
updatePathSteps(
compact(updatedPathSteps).filter(
updatePathSteps({
pathSteps: compact(updatedPathSteps).filter(
(step) =>
('uic' in step && step.uic !== op.uic) || ('track' in step && step.track !== op.track)
)
)
),
})
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ const TypeAndPathV2 = ({ setPathProperties }: PathfindingProps) => {
stopFor: i === opList.length - 1 ? '0' : undefined,
};
});
dispatch(updatePathSteps(pathSteps));
dispatch(updatePathSteps({ pathSteps, resetPowerRestrictions: true }));
}
}
// TODO TS2 : test errors display after core / editoast connexion for pathProperties
Expand Down
Loading

0 comments on commit 9abcaa4

Please sign in to comment.