forked from equinor/flotilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlertContext.tsx
More file actions
379 lines (338 loc) · 15.2 KB
/
AlertContext.tsx
File metadata and controls
379 lines (338 loc) · 15.2 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { createContext, FC, ReactNode, useContext, useEffect, useState } from 'react'
import { addMinutes, max } from 'date-fns'
import { Mission, MissionStatus } from 'models/Mission'
import { FailedMissionAlertContent, FailedMissionAlertListContent } from 'components/Alerts/FailedMissionAlert'
import { SignalREventLabels, useSignalRContext } from './SignalRContext'
import { Alert } from 'models/Alert'
import { useAssetContext } from './AssetContext'
import { RobotStatus } from 'models/Robot'
import {
FailedAlertContent,
FailedAlertListContent,
FailedAutoMissionAlertContent,
} from 'components/Alerts/FailedAlertContent'
import { convertUTCDateToLocalDate } from 'utils/StringFormatting'
import { AlertCategory } from 'components/Alerts/AlertsBanner'
import { DockAlertContent, DockAlertListContent } from 'components/Alerts/DockAlert'
import { useLanguageContext } from './LanguageContext'
import { FailedRequestAlertContent, FailedRequestAlertListContent } from 'components/Alerts/FailedRequestAlert'
import { InfoAlertContent, InfoAlertListContent } from 'components/Alerts/InfoAlertContent'
import { useBackendApi } from 'api/UseBackendApi'
import { AuthContext } from './AuthContext'
import { InstallationContext } from './InstallationContext'
export enum AlertType {
MissionFail,
RequestFail,
DockFail,
BlockedRobot,
RequestDock,
DismissDock,
DockSuccess,
AutoScheduleFail,
InfoAlert,
}
const alertTypeEnumMap: { [key: string]: AlertType } = {
DockFailure: AlertType.DockFail,
generalFailure: AlertType.RequestFail,
AutoScheduleFail: AlertType.AutoScheduleFail,
skipAutoMission: AlertType.InfoAlert,
}
export type AlertDictionaryType = {
[key in AlertType]?: { content: ReactNode | undefined; dismissFunction: () => void; alertCategory: AlertCategory }
}
interface IAlertContext {
alerts: AlertDictionaryType
setAlert: (source: AlertType, alert: ReactNode, category: AlertCategory) => void
clearAlerts: () => void
clearAlert: (source: AlertType) => void
listAlerts: AlertDictionaryType
setListAlert: (source: AlertType, listAlert: ReactNode, category: AlertCategory) => void
clearListAlerts: () => void
clearListAlert: (source: AlertType) => void
}
interface Props {
children: React.ReactNode
}
const defaultAlertInterface = {
alerts: {},
setAlert: () => {},
clearAlerts: () => {},
clearAlert: () => {},
listAlerts: {},
setListAlert: () => {},
clearListAlerts: () => {},
clearListAlert: () => {},
}
export interface AutoScheduleFailedMissionDict {
[key: string]: string
}
const AlertContext = createContext<IAlertContext>(defaultAlertInterface)
export const AlertProvider: FC<Props> = ({ children }) => {
const [alerts, setAlerts] = useState<AlertDictionaryType>(defaultAlertInterface.alerts)
const [listAlerts, setListAlerts] = useState<AlertDictionaryType>(defaultAlertInterface.listAlerts)
const [recentFailedMissions, setRecentFailedMissions] = useState<Mission[]>([])
const { registerEvent, connectionReady } = useSignalRContext()
const { TranslateText } = useLanguageContext()
const { enabledRobots } = useAssetContext()
const { installation } = useContext(InstallationContext)
const [autoScheduleFailedMissionDict, setAutoScheduleFailedMissionDict] = useState<AutoScheduleFailedMissionDict>(
JSON.parse(window.localStorage.getItem('autoScheduleFailedMissionDict') || '{}')
)
const backendApi = useBackendApi()
const { isAuthenticated } = useContext(AuthContext)
const pageSize: number = 100
// The default amount of minutes in the past for failed missions to generate an alert
const defaultTimeInterval: number = 10
// The maximum amount of minutes in the past for failed missions to generate an alert
const maxTimeInterval: number = 60
const dismissMissionFailTimeKey: string = 'lastMissionFailDismissalTime'
const setAlert = (source: AlertType, alert: ReactNode, category: AlertCategory) => {
setAlerts((oldAlerts) => {
return {
...oldAlerts,
[source]: { content: alert, dismissFunction: () => clearAlert(source), alertCategory: category },
}
})
}
const clearAlerts = () => setAlerts({})
const clearAlert = (source: AlertType) => {
if (source === AlertType.MissionFail) {
sessionStorage.setItem(dismissMissionFailTimeKey, JSON.stringify(Date.now()))
setRecentFailedMissions([])
}
if (source === AlertType.AutoScheduleFail) {
setAutoScheduleFailedMissionDict({})
window.localStorage.setItem('autoScheduleFailedMissionDict', JSON.stringify({}))
}
setAlerts((oldAlerts) => {
const newAlerts = { ...oldAlerts }
delete newAlerts[source]
return newAlerts
})
}
const setListAlert = (source: AlertType, listAlert: ReactNode, category: AlertCategory) => {
setListAlerts((oldListAlerts) => {
return {
...oldListAlerts,
[source]: {
content: listAlert,
dismissFunction: () => clearListAlert(source),
alertCategory: category,
},
}
})
}
const clearListAlerts = () => setListAlerts({})
const clearListAlert = (source: AlertType) => {
if (source === AlertType.MissionFail)
sessionStorage.setItem(dismissMissionFailTimeKey, JSON.stringify(Date.now()))
if (source === AlertType.AutoScheduleFail) {
setAutoScheduleFailedMissionDict({})
window.localStorage.setItem('autoScheduleFailedMissionDict', JSON.stringify({}))
}
setListAlerts((oldListAlerts) => {
const newListAlerts = { ...oldListAlerts }
delete newListAlerts[source]
return newListAlerts
})
}
const getLastDismissalTime = (): Date => {
const sessionValue = sessionStorage.getItem(dismissMissionFailTimeKey)
if (sessionValue === null || sessionValue === '') {
return addMinutes(Date.now(), -defaultTimeInterval)
} else {
// If last dismissal time was more than {MaxTimeInterval} minutes ago, use the limit value instead
return max([addMinutes(Date.now(), -maxTimeInterval), JSON.parse(sessionValue)])
}
}
// Set the initial failed missions when loading the page or changing installations
useEffect(() => {
if (!isAuthenticated) return
const updateRecentFailedMissions = () => {
const lastDismissTime: Date = getLastDismissalTime()
backendApi
.getMissionRuns({
installationCode: installation.installationCode,
statuses: [MissionStatus.Failed],
pageSize: pageSize,
})
.then((missions) => {
const newRecentFailedMissions = missions.content.filter(
(m) =>
convertUTCDateToLocalDate(new Date(m.endTime!)) > lastDismissTime &&
m.installationCode!.toLocaleLowerCase() ===
installation.installationCode.toLocaleLowerCase()
)
setRecentFailedMissions(newRecentFailedMissions)
})
.catch(() => {
setAlert(
AlertType.RequestFail,
<FailedRequestAlertContent
translatedMessage={TranslateText('Failed to retrieve failed missions')}
/>,
AlertCategory.ERROR
)
setListAlert(
AlertType.RequestFail,
<FailedRequestAlertListContent
translatedMessage={TranslateText('Failed to retrieve failed missions')}
/>,
AlertCategory.ERROR
)
})
}
if (!recentFailedMissions || recentFailedMissions.length === 0) updateRecentFailedMissions()
}, [installation])
// Register a signalR event handler that listens for new failed missions
useEffect(() => {
if (connectionReady) {
registerEvent(SignalREventLabels.missionRunFailed, (username: string, message: string) => {
const newFailedMission: Mission = JSON.parse(message)
const lastDismissTime: Date = getLastDismissalTime()
setRecentFailedMissions((failedMissions) => {
if (
!newFailedMission.installationCode ||
newFailedMission.installationCode.toLocaleLowerCase() !==
installation.installationCode.toLocaleLowerCase()
)
return failedMissions // Ignore missions for other installations
// Ignore missions shortly after the user dismissed the last one
if (convertUTCDateToLocalDate(new Date(newFailedMission.endTime!)) <= lastDismissTime)
return failedMissions
const isDuplicate = failedMissions.filter((m) => m.id === newFailedMission.id).length > 0
if (isDuplicate) return failedMissions // Ignore duplicate failed missions
return [...failedMissions, newFailedMission]
})
})
}
}, [registerEvent, connectionReady, installation])
useEffect(() => {
if (connectionReady) {
registerEvent(SignalREventLabels.alert, (username: string, message: string) => {
const backendAlert: Alert = JSON.parse(message)
if (
backendAlert.installationCode.toLocaleLowerCase() !==
installation.installationCode.toLocaleLowerCase()
)
return
const alertType = alertTypeEnumMap[backendAlert.alertCode]
if (backendAlert.robotId !== null && !enabledRobots.filter((r) => r.id === backendAlert.robotId)) return
if (alertType === AlertType.AutoScheduleFail) {
const newAutoScheduleFailedMissionDict: AutoScheduleFailedMissionDict = {
...autoScheduleFailedMissionDict,
}
newAutoScheduleFailedMissionDict[backendAlert.alertTitle] = backendAlert.alertMessage
setAutoScheduleFailedMissionDict(newAutoScheduleFailedMissionDict)
window.localStorage.setItem(
'autoScheduleFailedMissionDict',
JSON.stringify(newAutoScheduleFailedMissionDict)
)
return
}
if (alertType === AlertType.InfoAlert) {
setAlert(
alertType,
<InfoAlertContent title={backendAlert.alertTitle} message={backendAlert.alertMessage} />,
AlertCategory.INFO
)
setListAlert(
alertType,
<InfoAlertListContent title={backendAlert.alertTitle} message={backendAlert.alertMessage} />,
AlertCategory.INFO
)
} else {
setAlert(
alertType,
<FailedAlertContent title={backendAlert.alertTitle} message={backendAlert.alertMessage} />,
AlertCategory.ERROR
)
setListAlert(
alertType,
<FailedAlertListContent title={backendAlert.alertTitle} message={backendAlert.alertMessage} />,
AlertCategory.ERROR
)
}
})
}
}, [registerEvent, connectionReady, installation, enabledRobots])
useEffect(() => {
if (recentFailedMissions.length > 0) {
setAlert(
AlertType.MissionFail,
<FailedMissionAlertContent missions={recentFailedMissions} />,
AlertCategory.ERROR
)
setListAlert(
AlertType.MissionFail,
<FailedMissionAlertListContent missions={recentFailedMissions} />,
AlertCategory.ERROR
)
}
}, [recentFailedMissions])
useEffect(() => {
if (Object.keys(autoScheduleFailedMissionDict).length > 0) {
setListAlert(
AlertType.AutoScheduleFail,
<FailedAutoMissionAlertContent autoScheduleFailedMissionDict={autoScheduleFailedMissionDict} />,
AlertCategory.ERROR
)
setAlert(
AlertType.AutoScheduleFail,
<FailedAutoMissionAlertContent autoScheduleFailedMissionDict={autoScheduleFailedMissionDict} />,
AlertCategory.ERROR
)
}
}, [connectionReady, autoScheduleFailedMissionDict])
const robotsWithFrozenQueue = enabledRobots.filter((robot) => robot.status === RobotStatus.Lockdown)
const getActiveSendToDockAlertType = () => {
if (robotsWithFrozenQueue.length === 0) return undefined
else if (robotsWithFrozenQueue.find((robot) => robot.status !== RobotStatus.Home)) return AlertType.RequestDock
else return AlertType.DockSuccess
}
const [activeSendToDockAlertType, setActiveSendToDockAlertType] = useState<AlertType | undefined>(
getActiveSendToDockAlertType()
)
useEffect(() => {
let newActiveSendToDockAlertType = getActiveSendToDockAlertType()
if (activeSendToDockAlertType === newActiveSendToDockAlertType) return
if (activeSendToDockAlertType !== undefined && newActiveSendToDockAlertType === undefined) {
newActiveSendToDockAlertType = AlertType.DismissDock
}
setActiveSendToDockAlertType(newActiveSendToDockAlertType)
}, [robotsWithFrozenQueue])
useEffect(() => {
clearListAlert(AlertType.DismissDock)
clearAlert(AlertType.DismissDock)
clearListAlert(AlertType.RequestDock)
clearAlert(AlertType.RequestDock)
clearListAlert(AlertType.DockSuccess)
clearAlert(AlertType.DockSuccess)
if (activeSendToDockAlertType === undefined) return
const alertCategory =
activeSendToDockAlertType === AlertType.RequestDock ? AlertCategory.WARNING : AlertCategory.INFO
setListAlert(
AlertType.RequestDock,
<DockAlertListContent alertType={activeSendToDockAlertType} />,
alertCategory
)
setAlert(AlertType.RequestDock, <DockAlertContent alertType={activeSendToDockAlertType} />, alertCategory)
}, [activeSendToDockAlertType])
return (
<AlertContext.Provider
value={{
alerts,
setAlert,
clearAlerts,
clearAlert,
listAlerts,
setListAlert,
clearListAlerts,
clearListAlert,
}}
>
{children}
</AlertContext.Provider>
)
}
export const useAlertContext = () => useContext(AlertContext)