-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseEditStopBasicDetails.ts
More file actions
305 lines (281 loc) · 9.34 KB
/
useEditStopBasicDetails.ts
File metadata and controls
305 lines (281 loc) · 9.34 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import { gql } from '@apollo/client';
import isEqual from 'lodash/isEqual';
import merge from 'lodash/merge';
import { useTranslation } from 'react-i18next';
import {
EditStopMutationVariables,
RouteUniqueFieldsFragment,
ServicePatternScheduledStopPoint,
StopRegistryNameType,
StopRegistryStopPlaceInput,
useEditStopMutation,
useGetStopWithRouteGraphDataByIdLazyQuery,
useUpdateStopPlaceMutation,
} from '../../../../../generated/graphql';
import {
PartialScheduledStopPointSetInput,
mapStopResultToStop,
} from '../../../../../graphql';
import { StopWithDetails } from '../../../../../types';
import {
InternalError,
KnownValueKey,
TimingPlaceRequiredError,
defaultTo,
patchAlternativeNames,
patchKeyValues,
showDangerToast,
} from '../../../../../utils';
import { useValidateTimingSettings } from '../../../../map/stops/hooks/useValidateTimingSettings';
import { decodeQuayPrivateCodeType } from '../../../utils/decodeQuayPrivateCodeType';
import { getQuayIdsFromStopExcept } from '../useGetStopDetails';
import { StopBasicDetailsFormState } from './basic-details-form/schema';
type EditRoutesAndLinesParams = {
readonly stopId: UUID;
readonly state: StopBasicDetailsFormState;
};
// TODO: Go through this. Some of it can be deleted, but realised that the label name change conflicts are currently
// not handled here and they should. (just by changing the label should remove the stop from routes it is being used by)
type EditRoutesAndLinesChanges = {
readonly stopId: UUID;
readonly stopLabel: string;
readonly patch: PartialScheduledStopPointSetInput;
readonly editedStop: ServicePatternScheduledStopPoint;
readonly deleteStopFromRoutes: ReadonlyArray<RouteUniqueFieldsFragment>;
readonly deleteStopFromJourneyPatternIds?: ReadonlyArray<UUID>;
readonly conflicts?: ReadonlyArray<ServicePatternScheduledStopPoint>;
};
type EditTiamatParams = {
readonly state: StopBasicDetailsFormState;
readonly stop: StopWithDetails;
};
const GQL_UPDATE_STOP_PLACE = gql`
mutation UpdateStopPlace($input: stop_registry_StopPlaceInput!) {
stop_registry {
mutateStopPlace(StopPlace: $input) {
...stop_place_details
}
}
}
`;
export const useEditStopBasicDetails = () => {
const { t } = useTranslation();
const [editStopMutation] = useEditStopMutation();
const [updateStopPlaceMutation] = useUpdateStopPlaceMutation();
const [getStopWithRouteGraphData] =
useGetStopWithRouteGraphDataByIdLazyQuery();
const [validateTimingSettings] = useValidateTimingSettings();
const mapFormStateToRoutesAndLinesDbInput = (
state: StopBasicDetailsFormState,
) => {
const input = {
label: state.label,
timing_place_id: state.timingPlaceId,
};
return input;
};
// prepare variables for mutation and validate if it's even allowed
// try to produce a changeset that can be displayed on an explanatory UI
const prepareEditForRoutesAndLinesDb = async ({
stopId,
state,
}: EditRoutesAndLinesParams) => {
const patch = mapFormStateToRoutesAndLinesDbInput(state);
const stopWithRoutesResult = await getStopWithRouteGraphData({
variables: { stopId },
});
const stopWithRouteGraphData = mapStopResultToStop(stopWithRoutesResult);
// data model and form validation should ensure that
// label always exists
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const stopLabel = defaultTo(patch.label, stopWithRouteGraphData?.label)!;
if (!stopWithRouteGraphData) {
throw new InternalError(`Could not find stop with id ${stopId}`);
}
// validate stop's timing settings in journey patterns if stop's timing place has been changed
const newTimingPlaceId = patch.timing_place_id;
const oldTimingPlaceId = stopWithRouteGraphData.timing_place_id;
const hasTimingPlaceIdChanged = !isEqual(
newTimingPlaceId,
oldTimingPlaceId,
);
if (hasTimingPlaceIdChanged) {
await validateTimingSettings({
stopLabel,
timingPlaceId: newTimingPlaceId,
});
}
// changes that will always be applied
const defaultChanges = {
stopId,
stopLabel,
patch,
deleteStopFromRoutes: [],
deleteStopFromJourneyPatterns: [],
};
const finalChanges: EditRoutesAndLinesChanges = {
...defaultChanges,
// the final state of the stop that will be after patching
editedStop: merge({}, stopWithRouteGraphData, defaultChanges.patch),
};
return finalChanges;
};
const mapEditChangesToRoutesAndLinesDbVariables = (
changes: EditRoutesAndLinesChanges,
) => {
const variables: EditStopMutationVariables = {
stop_id: changes.stopId,
stop_label: changes.stopLabel,
stop_patch: changes.patch,
delete_from_journey_pattern_ids:
changes.deleteStopFromJourneyPatternIds ?? [],
};
return { variables };
};
const updateRoutesAndLinesStop = async (
editParams: EditRoutesAndLinesParams,
) => {
const changesToRoutesAndLinesDb =
await prepareEditForRoutesAndLinesDb(editParams);
const variablesForRoutesAndLinesDb =
mapEditChangesToRoutesAndLinesDbVariables(changesToRoutesAndLinesDb);
await editStopMutation(variablesForRoutesAndLinesDb);
};
const mapStopEditChangesToTiamatDbInput = ({
state,
stop,
}: EditTiamatParams): StopRegistryStopPlaceInput => {
const stopPlaceId = stop.stop_place?.id;
const stopPlaceQuayId = stop.stop_place_ref;
const otherQuays = getQuayIdsFromStopExcept(stop, stopPlaceQuayId);
return {
id: stopPlaceId,
name: {
lang: 'fin',
value: state.nameFin,
},
alternativeNames: patchAlternativeNames(stop.stop_place, [
{
name: { lang: 'swe', value: state.nameSwe },
nameType: StopRegistryNameType.Translation,
},
{
name: { lang: 'fin', value: state.abbreviationFin },
nameType: StopRegistryNameType.Other,
},
{
name: { lang: 'swe', value: state.abbreviationSwe },
nameType: StopRegistryNameType.Other,
},
{
name: { lang: 'fin', value: state.nameLongFin },
nameType: StopRegistryNameType.Alias,
},
{
name: { lang: 'swe', value: state.nameLongSwe },
nameType: StopRegistryNameType.Alias,
},
]),
keyValues: patchKeyValues(stop.stop_place, [
{
key: KnownValueKey.ValidityStart,
values: stop.validity_start ? [stop.validity_start.toISODate()] : [],
},
{
key: KnownValueKey.ValidityEnd,
values: stop.validity_end ? [stop.validity_end.toISODate()] : [],
},
]),
quays: [
...otherQuays,
{
publicCode: state.label,
privateCode: {
value: state.privateCode,
type: decodeQuayPrivateCodeType(state.privateCode),
},
id: stopPlaceQuayId,
description: { value: state.locationFin, lang: 'fin' },
alternativeNames: patchAlternativeNames(stop.stop_place, [
{
name: { lang: 'swe', value: state.locationSwe },
nameType: StopRegistryNameType.Other,
},
]),
keyValues: patchKeyValues(stop.quay, [
{
key: KnownValueKey.RailReplacement,
values: state.stopTypes.railReplacement
? [state.stopTypes.railReplacement?.toString()]
: [],
},
{
key: KnownValueKey.Virtual,
values: state.stopTypes.virtual
? [state.stopTypes.virtual?.toString()]
: [],
},
{
key: KnownValueKey.ElyNumber,
values: state.elyNumber ? [state.elyNumber] : [],
},
{
key: KnownValueKey.StopState,
values: state.stopState ? [state.stopState] : [],
},
]),
versionComment:
state.reasonForChange !== '' ? state.reasonForChange : null,
},
],
transportMode: state.transportMode,
};
};
const prepareEditForTiamatDb = ({ state, stop }: EditTiamatParams) => {
return {
input: mapStopEditChangesToTiamatDbInput({
state,
stop,
}),
};
};
const updateTiamatStopPlace = async (editParams: EditTiamatParams) => {
const changesToTiamatDb = prepareEditForTiamatDb(editParams);
await updateStopPlaceMutation({
variables: changesToTiamatDb,
refetchQueries: ['GetStopDetails', 'GetLatestQuayChange'],
});
};
const saveStopPlaceDetails = async ({
state,
stop,
}: {
state: StopBasicDetailsFormState;
stop: StopWithDetails;
}) => {
await updateRoutesAndLinesStop({
state,
stopId: stop.scheduled_stop_point_id,
});
await updateTiamatStopPlace({
state,
stop,
});
};
// default handler that can be used to show error messages as toast
// in case an exception is thrown
const defaultErrorHandler = (err: Error) => {
if (err instanceof TimingPlaceRequiredError) {
showDangerToast(
t('stops.timingPlaceRequired', { routeLabels: err.message }),
);
return;
}
// if other error happened, show the generic error message
showDangerToast(`${t('errors.saveFailed')}, ${err}`);
};
return {
saveStopPlaceDetails,
defaultErrorHandler,
};
};