-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathusePathfinding.ts
291 lines (253 loc) · 9.81 KB
/
usePathfinding.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
import { useCallback, useEffect, useState } from 'react';
import { 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 {
IncompatibleConstraints,
PathfindingInputError,
PathfindingResultSuccess,
PostInfraByInfraIdPathPropertiesApiArg,
} from 'common/api/osrdEditoastApi';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import { useOsrdConfActions, useOsrdConfSelectors } from 'common/osrdContext';
import {
formatSuggestedOperationalPoints,
getPathfindingQuery,
matchPathStepAndOp,
} from 'modules/pathfinding/utils';
import { useStoreDataForRollingStockSelector } from 'modules/rollingStock/components/RollingStockSelector/useStoreDataForRollingStockSelector';
import type { SuggestedOP } from 'modules/trainschedule/components/ManageTrainSchedule/types';
import { setFailure, setWarning } from 'reducers/main';
import type { PathStep } from 'reducers/osrdconf/types';
import { useAppDispatch } from 'store';
import { isEmptyArray } from 'utils/array';
import { castErrorToFailure } from 'utils/error';
import useInfraStatus from './useInfraStatus';
import type { PathfindingState } from '../types';
const initialPathfindingState = {
isRunning: false,
isDone: false,
isMissingParam: false,
};
const usePathfinding = (
setPathProperties: (pathProperties?: ManageTrainSchedulePathProperties) => void
) => {
const { t } = useTranslation(['operationalStudies/manageTrainSchedule']);
const dispatch = useAppDispatch();
const { getPathSteps, getPowerRestriction } = useOsrdConfSelectors();
const pathSteps = useSelector(getPathSteps);
const powerRestrictions = useSelector(getPowerRestriction);
const { infra, reloadCount, setIsInfraError } = useInfraStatus();
const { rollingStock } = useStoreDataForRollingStockSelector();
const [pathfindingState, setPathfindingState] =
useState<PathfindingState>(initialPathfindingState);
// isInitialized is used to prevent the pathfinding to be launched multiple times
// and especially to prevent the power restrictions to be reset
const [isInitialized, setIsInitialized] = useState(false);
const [postPathfindingBlocks] =
osrdEditoastApi.endpoints.postInfraByInfraIdPathfindingBlocks.useLazyQuery();
const [postPathProperties] =
osrdEditoastApi.endpoints.postInfraByInfraIdPathProperties.useLazyQuery();
const { updatePathSteps, replaceItinerary } = useOsrdConfActions();
const { infraId } = useScenarioContext();
const setIsMissingParam = () =>
setPathfindingState({ ...initialPathfindingState, isMissingParam: true });
const setIsRunning = () => setPathfindingState({ ...initialPathfindingState, isRunning: true });
const setIsDone = () => setPathfindingState({ ...initialPathfindingState, isDone: true });
const setError = (error?: string) => setPathfindingState({ ...initialPathfindingState, error });
const handleInvalidPathItems = (
steps: (PathStep | null)[],
invalidPathItems: Extract<PathfindingInputError, { error_type: 'invalid_path_items' }>['items']
) => {
// TODO: we currently only handle invalid pathSteps with trigram. We will have to do it for trackOffset, opId and uic too.
const invalidTrigrams = invalidPathItems
.map((item) => {
if ('trigram' in item.path_item) {
return item.path_item.trigram;
}
return null;
})
.filter((trigram): trigram is string => trigram !== null);
if (invalidTrigrams.length > 0) {
const updatedPathSteps = steps.map((step) => {
if (step && 'trigram' in step && invalidTrigrams.includes(step.trigram)) {
return { ...step, isInvalid: true };
}
return step;
});
// eslint-disable-next-line @typescript-eslint/no-use-before-define
launchPathfinding(updatedPathSteps);
} else {
setError(t('missingPathSteps'));
dispatch(setFailure({ name: t('pathfindingError'), message: t('missingPathSteps') }));
}
};
const populateStoreWithPathfinding = async (
pathStepsInput: PathStep[],
pathResult: PathfindingResultSuccess,
incompatibleConstraints?: IncompatibleConstraints
) => {
const pathPropertiesParams: PostInfraByInfraIdPathPropertiesApiArg = {
infraId,
props: ['electrifications', 'geometry', 'operational_points'],
pathPropertiesInput: {
track_section_ranges: pathResult.track_section_ranges,
},
};
const { electrifications, geometry, operational_points } =
await postPathProperties(pathPropertiesParams).unwrap();
if (!electrifications || !geometry || !operational_points) {
return;
}
const suggestedOperationalPoints: SuggestedOP[] = formatSuggestedOperationalPoints(
operational_points,
geometry,
pathResult.length
);
// We update existing pathsteps with coordinates, positionOnPath and kp corresponding to the new pathfinding result
const updatedPathSteps: (PathStep | null)[] = pathStepsInput.map((step, i) => {
if (!step) return step;
const correspondingOp = suggestedOperationalPoints.find((suggestedOp) =>
matchPathStepAndOp(step, suggestedOp)
);
const theoreticalMargin = i === 0 ? step.theoreticalMargin || '0%' : step.theoreticalMargin;
const stopFor = i === pathStepsInput.length - 1 && !step.stopFor ? '0' : step.stopFor;
const stopType = i === pathStepsInput.length - 1 && !step.stopFor ? undefined : step.stopType;
return {
...step,
positionOnPath: pathResult.path_item_positions[i],
stopFor,
stopType,
theoreticalMargin,
...(correspondingOp && {
name: correspondingOp.name,
uic: correspondingOp.uic,
secondary_code: correspondingOp.ch,
kp: correspondingOp.kp,
coordinates: correspondingOp.coordinates,
}),
};
});
if (!isEmptyArray(powerRestrictions)) {
dispatch(
setWarning({
title: t('warningMessages.pathfindingChange'),
text: t('warningMessages.powerRestrictionsReset'),
})
);
}
dispatch(updatePathSteps(updatedPathSteps));
setPathProperties({
electrifications,
geometry,
suggestedOperationalPoints,
length: pathResult.length,
trackSectionRanges: pathResult.track_section_ranges,
incompatibleConstraints,
});
};
const launchPathfinding = useCallback(
async (steps: (PathStep | null)[]) => {
dispatch(replaceItinerary(steps));
setPathProperties(undefined);
if (steps.some((step) => step === null)) {
setIsMissingParam();
return;
}
if (infra?.state !== 'CACHED') {
return;
}
setIsRunning();
const pathfindingInput = getPathfindingQuery({
infraId,
rollingStock,
pathSteps: steps.filter((step) => step !== null && !step.isInvalid),
});
if (!pathfindingInput) {
setIsMissingParam();
return;
}
try {
const pathfindingResult = await postPathfindingBlocks(pathfindingInput).unwrap();
if (pathfindingResult.status === 'success') {
await populateStoreWithPathfinding(
steps.map((step) => step!),
pathfindingResult
);
setIsDone();
return;
}
const incompatibleConstraintsCheck =
pathfindingResult.failed_status === 'pathfinding_not_found' &&
pathfindingResult.error_type === 'incompatible_constraints';
if (incompatibleConstraintsCheck) {
await populateStoreWithPathfinding(
steps.map((step) => step!),
pathfindingResult.relaxed_constraints_path,
pathfindingResult.incompatible_constraints
);
setError(t(`pathfindingErrors.${pathfindingResult.error_type}`));
return;
}
const hasInvalidPathItems =
pathfindingResult.failed_status === 'pathfinding_input_error' &&
pathfindingResult.error_type === 'invalid_path_items';
if (hasInvalidPathItems) {
handleInvalidPathItems(steps, pathfindingResult.items);
return;
}
let error: string;
if (pathfindingResult.failed_status === 'internal_error') {
const translationKey = pathfindingResult.core_error.type.startsWith('core:')
? pathfindingResult.core_error.type.replace('core:', '')
: pathfindingResult.core_error.type;
error = t(`coreErrors.${translationKey}`, {
defaultValue: pathfindingResult.core_error.message,
});
} else {
error = t(`pathfindingErrors.${pathfindingResult.error_type}`);
}
setError(error);
} catch (e) {
if (isObject(e)) {
let error;
if ('error' in e) {
dispatch(setFailure(castErrorToFailure(e, { name: t('pathfinding') })));
error = 'failedRequest';
} else if ('data' in e && isObject(e.data) && 'message' in e.data) {
error = e.data.message as string;
if (e.data.message === 'Infra not loaded' || e.data.message === 'Invalid version') {
setIsInfraError(true);
}
}
setError(error);
}
}
},
[rollingStock, infra]
);
useEffect(() => {
if (isInitialized && infra?.state === 'CACHED') {
launchPathfinding(pathSteps);
}
}, [infra?.state]);
useEffect(() => {
if (isInitialized) {
launchPathfinding(pathSteps);
}
}, [rollingStock]);
useEffect(() => {
setIsInitialized(true);
}, []);
return {
launchPathfinding,
pathfindingState,
infraInfo: {
infra,
reloadCount,
},
};
};
export default usePathfinding;