-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathuseSetupItineraryForTrainUpdate.ts
258 lines (229 loc) · 9.21 KB
/
useSetupItineraryForTrainUpdate.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
import { useEffect } from 'react';
import { type Position } from '@turf/helpers';
import { omit } from 'lodash';
import { useSelector } from 'react-redux';
import {
osrdEditoastApi,
type PathItemLocation,
type PostInfraByInfraIdPathPropertiesApiArg,
type PostInfraByInfraIdPathfindingBlocksApiArg,
type RollingStockWithLiveries,
type TrainScheduleResult,
type PathfindingResult,
} from 'common/api/osrdEditoastApi';
import { useOsrdConfActions, useOsrdConfSelectors } from 'common/osrdContext';
import {
formatSuggestedOperationalPoints,
matchPathStepAndOp,
upsertPathStepsInOPs,
} from 'modules/pathfinding/utils';
import { getSupportedElectrification, isThermal } from 'modules/rollingStock/helpers/electric';
import { adjustConfWithTrainToModify } from 'modules/trainschedule/components/ManageTrainSchedule/helpers/adjustConfWithTrainToModify';
import type { SuggestedOP } from 'modules/trainschedule/components/ManageTrainSchedule/types';
import { setFailure } from 'reducers/main';
import type { OperationalStudiesConfSliceActions } from 'reducers/osrdconf/operationalStudiesConf';
import type { PathStep } from 'reducers/osrdconf/types';
import { useAppDispatch } from 'store';
import { castErrorToFailure } from 'utils/error';
import { getPointCoordinates } from 'utils/geometry';
import { mmToM } from 'utils/physics';
import { ISO8601Duration2sec } from 'utils/timeManipulation';
import type { ManageTrainSchedulePathProperties } from '../types';
type ItineraryForTrainUpdate = {
pathSteps: (PathStep | null)[];
pathProperties: ManageTrainSchedulePathProperties;
};
/**
* create pathSteps in the case pathfinding fails or the train is imported from NGE
*/
const computeBasePathSteps = (trainSchedule: TrainScheduleResult) =>
trainSchedule.path.map((step) => {
const correspondingSchedule = trainSchedule.schedule?.find(
(schedule) => schedule.at === step.id
);
const {
arrival,
stop_for: stopFor,
locked,
reception_signal: receptionSignal,
} = correspondingSchedule || {};
const stepWithoutSecondaryCode = omit(step, ['secondary_code']);
if ('track' in stepWithoutSecondaryCode) {
stepWithoutSecondaryCode.offset = mmToM(stepWithoutSecondaryCode.offset!);
}
let name;
if ('trigram' in step) {
name = step.trigram + (step.secondary_code ? `/${step.secondary_code}` : '');
} else if ('uic' in step) {
name = step.uic.toString();
} else if ('operational_point' in step) {
name = step.operational_point;
}
return {
...stepWithoutSecondaryCode,
ch: 'secondary_code' in step ? step.secondary_code : undefined,
name,
arrival, // ISODurationString
stopFor: stopFor ? ISO8601Duration2sec(stopFor).toString() : stopFor,
locked,
receptionSignal,
} as PathStep;
});
export function updatePathStepsFromOperationalPoints(
pathSteps: PathStep[],
suggestedOperationalPoints: SuggestedOP[],
pathfindingResult: Extract<PathfindingResult, { status: 'success' }>,
stepsCoordinates: Position[]
) {
const updatedPathSteps: PathStep[] = pathSteps.map((step, i) => {
const correspondingOp = suggestedOperationalPoints.find((suggestedOp) =>
matchPathStepAndOp(step, suggestedOp)
);
const { kp, name, ch } = correspondingOp || step;
return {
...step,
ch,
kp,
name,
positionOnPath: pathfindingResult.path_item_positions[i],
coordinates: stepsCoordinates[i],
};
});
return updatedPathSteps;
}
const useSetupItineraryForTrainUpdate = (
setPathProperties: (pathProperties: ManageTrainSchedulePathProperties) => void,
trainIdToEdit: number
) => {
const { getInfraID, getUsingElectricalProfiles } = useOsrdConfSelectors();
const infraId = useSelector(getInfraID);
const usingElectricalProfiles = useSelector(getUsingElectricalProfiles);
const dispatch = useAppDispatch();
const osrdActions = useOsrdConfActions() as OperationalStudiesConfSliceActions;
const [getTrainScheduleById] = osrdEditoastApi.endpoints.getTrainScheduleById.useLazyQuery({});
const [getRollingStockByName] =
osrdEditoastApi.endpoints.getRollingStockNameByRollingStockName.useLazyQuery();
const [postPathfindingBlocks] =
osrdEditoastApi.endpoints.postInfraByInfraIdPathfindingBlocks.useMutation();
const [postPathProperties] =
osrdEditoastApi.endpoints.postInfraByInfraIdPathProperties.useMutation();
useEffect(() => {
const computeItineraryForTrainUpdate = async (
trainSchedule: TrainScheduleResult,
rollingStock: RollingStockWithLiveries
): Promise<ItineraryForTrainUpdate | null> => {
if (!infraId) {
return null;
}
// TODO TS2 : Next part might not be needed (except to updePathSteps), we need inly trainSchedulePath and
// rolling stock infos to relaunch the pathfinding. Check for that in simulation results issue
const params: PostInfraByInfraIdPathfindingBlocksApiArg = {
infraId,
pathfindingInput: {
path_items: trainSchedule.path.map((item) =>
omit(item, ['id', 'deleted'])
) as PathItemLocation[],
rolling_stock_is_thermal: isThermal(rollingStock.effort_curves.modes),
rolling_stock_loading_gauge: rollingStock.loading_gauge,
rolling_stock_supported_electrifications: getSupportedElectrification(
rollingStock.effort_curves.modes
),
rolling_stock_supported_signaling_systems: rollingStock.supported_signaling_systems,
rolling_stock_maximum_speed: rollingStock.max_speed,
rolling_stock_length: rollingStock.length,
},
};
const pathfindingResult = await postPathfindingBlocks(params).unwrap();
if (pathfindingResult.status !== 'success') {
return null;
}
const pathPropertiesParams: PostInfraByInfraIdPathPropertiesApiArg = {
infraId,
props: ['electrifications', 'geometry', 'operational_points'],
pathPropertiesInput: {
track_section_ranges: pathfindingResult.track_section_ranges,
},
};
const { electrifications, geometry, operational_points } =
await postPathProperties(pathPropertiesParams).unwrap();
if (!electrifications || !geometry || !operational_points) {
return null;
}
const stepsCoordinates = pathfindingResult.path_item_positions.map((position) =>
getPointCoordinates(geometry, pathfindingResult.length, position)
);
const suggestedOperationalPoints: SuggestedOP[] = formatSuggestedOperationalPoints(
operational_points,
geometry,
pathfindingResult.length
);
const computedpathSteps = computeBasePathSteps(trainSchedule);
const updatedPathSteps: PathStep[] = updatePathStepsFromOperationalPoints(
computedpathSteps,
suggestedOperationalPoints,
pathfindingResult,
stepsCoordinates
);
const findCorrespondingMargin = (
stepId: string,
stepIndex: number,
margins: { boundaries: string[]; values: string[] }
) => {
// The first pathStep will never have its id in boundaries
if (stepIndex === 0) return margins.values[0] === 'none' ? undefined : margins.values[0];
const marginIndex = margins.boundaries.findIndex((boundaryId) => boundaryId === stepId);
return marginIndex !== -1 ? margins.values[marginIndex + 1] : undefined;
};
if (trainSchedule.margins) {
updatedPathSteps.forEach((step, index) => {
step.theoreticalMargin = findCorrespondingMargin(step.id, index, trainSchedule.margins!);
});
}
const allWaypoints = upsertPathStepsInOPs(suggestedOperationalPoints, updatedPathSteps);
return {
pathProperties: {
electrifications,
geometry,
suggestedOperationalPoints,
allWaypoints,
length: pathfindingResult.length,
trackSectionRanges: pathfindingResult.track_section_ranges,
},
pathSteps: updatedPathSteps,
};
// TODO TS2 : test errors display after core / editoast connexion for pathProperties
};
const setupItineraryForTrainUpdate = async () => {
if (!infraId) {
return;
}
const trainSchedule = await getTrainScheduleById({ id: trainIdToEdit }).unwrap();
let rollingStock: RollingStockWithLiveries | null = null;
let pathSteps: (PathStep | null)[] | undefined;
if (trainSchedule.rolling_stock_name) {
try {
rollingStock = await getRollingStockByName({
rollingStockName: trainSchedule.rolling_stock_name,
}).unwrap();
const itinerary = await computeItineraryForTrainUpdate(trainSchedule, rollingStock);
pathSteps = itinerary?.pathSteps;
if (itinerary?.pathProperties) {
setPathProperties(itinerary.pathProperties);
}
} catch (e) {
dispatch(setFailure(castErrorToFailure(e)));
}
}
adjustConfWithTrainToModify(
trainSchedule,
pathSteps || computeBasePathSteps(trainSchedule),
rollingStock?.id,
dispatch,
usingElectricalProfiles,
osrdActions
);
};
setupItineraryForTrainUpdate();
}, [trainIdToEdit]);
};
export default useSetupItineraryForTrainUpdate;