generated from VeeamCommunity/veeamcommunity-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DashboardScreen.js
502 lines (459 loc) · 16 KB
/
DashboardScreen.js
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import React, { useEffect, useState } from 'react';
import { SafeAreaView, StyleSheet, Text, View, ScrollView, TouchableOpacity, Alert, Dimensions } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import qs from 'qs';
import { BarChart, PieChart } from "react-native-gifted-charts";
const screenWidth = Dimensions.get('window').width;
const DashboardScreen = () => {
const navigation = useNavigation();
const [jobStatuses, setJobStatuses] = useState([]);
const [jobCounts24h, setJobCounts24h] = useState({ success: 0, failed: 0, warning: 0 });
const [slaStatus, setSlaStatus] = useState(0);
const [backupPerformance7d, setBackupPerformance7d] = useState([]);
const [storageUsage, setStorageUsage] = useState({ used: 0, total: 0 });
// Inline bytesToSize function
const bytesToSize = (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
useEffect(() => {
const fetchJobStatuses = async () => {
try {
const baseUrl = await AsyncStorage.getItem('baseUrl');
let accessToken = await AsyncStorage.getItem('accessToken');
const refreshToken = await AsyncStorage.getItem('refreshToken');
const expiresIn = await AsyncStorage.getItem('expiresIn');
const currentTime = new Date().getTime();
if (currentTime >= parseInt(expiresIn)) {
// Token expired, refresh it
const response = await axios.post(`${baseUrl}/token`,
qs.stringify({ grant_type: 'refresh_token', refresh_token: refreshToken }),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
);
if (response.status >= 200 && response.status < 300) {
accessToken = response.data.access_token;
const newExpiresIn = new Date().getTime() + response.data.expires_in * 1000;
await AsyncStorage.setItem('accessToken', accessToken);
await AsyncStorage.setItem('expiresIn', newExpiresIn.toString());
} else {
throw new Error('Failed to refresh token');
}
}
const [jobResponse, agentJobResponse, vb365JobResponse] = await Promise.all([
axios.get(`${baseUrl}/infrastructure/backupServers/jobs`, {
headers: { Authorization: `Bearer ${accessToken}` }
}),
axios.get(`${baseUrl}/infrastructure/backupAgents/jobs`, {
headers: { Authorization: `Bearer ${accessToken}` }
}),
axios.get(`${baseUrl}/infrastructure/vb365Servers/organizations/jobs`, {
headers: { Authorization: `Bearer ${accessToken}` }
})
]);
if (jobResponse.status >= 200 && jobResponse.status < 300 && agentJobResponse.status >= 200 && agentJobResponse.status < 300 && vb365JobResponse.status >= 200 && vb365JobResponse.status < 300) {
const jobs = jobResponse.data.data;
const agentJobs = agentJobResponse.data.data;
const vb365Jobs = vb365JobResponse.data.data;
const allJobs = [...jobs, ...agentJobs, ...vb365Jobs];
setJobStatuses(allJobs);
const counts24h = { success: 0, warning: 0, failed: 0 };
const performanceData7d = {};
const twentyFourHoursAgo = new Date(currentTime - 24 * 60 * 60 * 1000);
const sevenDaysAgo = new Date(currentTime - 7 * 24 * 60 * 60 * 1000);
allJobs.forEach(job => {
const lastRunTime = new Date(job.lastRun);
// Last 24 hours job counts
if (lastRunTime >= twentyFourHoursAgo) {
if (job.status === 'Success' || job.lastStatus === 'Success') {
counts24h.success += 1;
} else if (job.status === 'Warning' || job.lastStatus === 'Warning') {
counts24h.warning += 1;
} else if (job.status === 'Failed' || job.lastStatus === 'Failed') {
counts24h.failed += 1;
}
}
// Last 7 days performance data
if (lastRunTime >= sevenDaysAgo) {
const dayKey = lastRunTime.toISOString().split('T')[0];
if (!performanceData7d[dayKey]) {
performanceData7d[dayKey] = { success: 0, warning: 0, failed: 0 };
}
if (job.status === 'Success' || job.lastStatus === 'Success') {
performanceData7d[dayKey].success += 1;
} else if (job.status === 'Warning' || job.lastStatus === 'Warning') {
performanceData7d[dayKey].warning += 1;
} else if (job.status === 'Failed' || job.lastStatus === 'Failed') {
performanceData7d[dayKey].failed += 1;
}
}
});
setJobCounts24h(counts24h);
const stackData = Object.entries(performanceData7d).map(([date, data]) => ({
stacks: [
{ value: data.success, color: 'green' },
{ value: data.warning, color: 'orange', marginBottom: 2 },
{ value: data.failed, color: 'red', marginBottom: 2 },
],
label: new Date(date).toLocaleDateString('en-US', { weekday: 'short' }),
}));
setBackupPerformance7d(stackData);
// Calculate SLA status
const totalJobs = counts24h.success + counts24h.warning + counts24h.failed;
const successfulJobs = counts24h.success + counts24h.warning;
const sla = totalJobs > 0 ? (successfulJobs / totalJobs) * 100 : 0;
setSlaStatus(sla.toFixed(2));
} else {
throw new Error('Failed to fetch job statuses');
}
} catch (error) {
console.error('Error fetching job statuses:', error);
Alert.alert('Error', 'Failed to fetch job statuses. Please try again later.');
}
};
const fetchStorageUsage = async () => {
try {
const baseUrl = await AsyncStorage.getItem('baseUrl');
const accessToken = await AsyncStorage.getItem('accessToken');
const response = await axios.get(`${baseUrl}/organizations/companies/sites/backupResources/usage`, {
headers: { Authorization: `Bearer ${accessToken}` }
});
if (response.status >= 200 && response.status < 300) {
const data = response.data.data[0];
setStorageUsage({
used: data.usedStorageQuota,
total: data.storageQuota
});
} else {
throw new Error('Failed to fetch storage usage');
}
} catch (error) {
console.error('Error fetching storage usage:', error);
Alert.alert('Error', 'Failed to fetch storage usage. Please try again later.');
}
};
fetchJobStatuses();
fetchStorageUsage();
}, []);
const renderJobStatus = (job, index) => {
const lastRunTime = new Date(job.lastRun);
const currentTime = new Date();
const isRecent = (currentTime - lastRunTime) / (1000 * 60 * 60) < 24; // within 24 hours
let statusColor = 'gray';
if (job.status === 'Success' || job.lastStatus === 'Success') {
statusColor = 'green';
} else if (job.status === 'Warning' || job.lastStatus === 'Warning') {
statusColor = 'orange';
} else if (job.status === 'Failed' || job.lastStatus === 'Failed') {
statusColor = 'red';
}
return (
<View key={index} style={styles.jobStatusContainer}>
<Text style={[styles.jobStatusText, { color: statusColor }]}>
{job.name}: {job.status || job.lastStatus} {isRecent ? '(Recent)' : ''}
</Text>
<Text style={styles.jobStatusSubText}>Last Run: {lastRunTime.toLocaleString()}</Text>
</View>
);
};
const handleShowJobDetails = () => {
navigation.navigate('JobDetails', { jobStatuses });
};
const handleShowThreatCenter = () => {
navigation.navigate('Threats'); // Changed from 'ThreatCenter' to 'Threats'
};
const handleShowBillingDashboard = () => {
navigation.navigate('BillingDashboard');
};
const renderBarChart = () => {
if (backupPerformance7d.length === 0) {
return <Text>No data available for chart</Text>;
}
try {
const stackData = backupPerformance7d.map(item => ({
stacks: [
{ value: Number(item.stacks[0].value) || 0, color: 'green' },
{ value: Number(item.stacks[1].value) || 0, color: 'orange', marginBottom: 2 },
{ value: Number(item.stacks[2].value) || 0, color: 'red', marginBottom: 2 },
],
label: item.label,
}));
const maxValue = Math.max(...stackData.map(item =>
item.stacks.reduce((sum, stack) => sum + stack.value, 0)
));
return (
<BarChart
width={screenWidth - 64}
height={220}
barWidth={32}
spacing={20}
noOfSections={5}
maxValue={maxValue > 0 ? maxValue : 1}
stackData={stackData}
barBorderRadius={4}
yAxisThickness={0}
xAxisThickness={0}
yAxisTextStyle={{ color: '#333' }}
xAxisLabelTextStyle={{ color: '#333', textAlign: 'center' }}
yAxisLabelTexts={['0', '25', '50', '75', '100']}
labelWidth={40}
xAxisLabelWidth={40}
rotateLabel
/>
);
} catch (error) {
console.error('Error rendering BarChart:', error);
return <Text>Error rendering chart</Text>;
}
};
const renderSLAChart = () => {
const slaValue = parseFloat(slaStatus);
let color;
if (slaValue >= 70) {
color = 'green'; // Same green as used in the bar chart
} else if (slaValue >= 50) {
color = 'orange';
} else {
color = 'red';
}
const pieData = [
{ value: slaValue, color: color },
{ value: 100 - slaValue, color: 'lightgray' }
];
return (
<View style={styles.slaChartContainer}>
<PieChart
donut
innerRadius={60}
radius={80}
data={pieData}
centerLabelComponent={() => {
return (
<View style={styles.slaCenterLabel}>
<Text style={[styles.slaPercentage, { color: color }]}>{slaStatus}%</Text>
<Text style={styles.slaSubtext}>Current compliance</Text>
</View>
);
}}
/>
</View>
);
};
const renderCloudRepositoryStatus = () => {
const usedPercentage = (storageUsage.used / storageUsage.total) * 100;
const freeSpace = storageUsage.total - storageUsage.used;
return (
<View style={styles.card}>
<Text style={styles.cardTitle}>Cloud Repository Status</Text>
<View style={styles.spaceContainer}>
<View style={styles.spaceBar}>
<View style={[styles.spaceUsed, { width: `${usedPercentage}%` }]} />
</View>
<View style={styles.spaceTextContainer}>
<Text style={styles.spaceText}>Used: <Text style={styles.usedSpace}>{bytesToSize(storageUsage.used)}</Text></Text>
<Text style={styles.spaceText}>Free: <Text style={styles.freeSpace}>{bytesToSize(freeSpace)}</Text></Text>
</View>
</View>
</View>
);
};
return (
<SafeAreaView style={styles.container}>
<ScrollView contentContainerStyle={styles.scrollContent}>
<View style={styles.card}>
<Text style={styles.cardTitle}>Backup Performance (Last 7 Days)</Text>
{renderBarChart()}
<View style={styles.legendContainer}>
<View style={styles.legendItem}>
<View style={[styles.legendColor, { backgroundColor: 'green' }]} />
<Text style={styles.legendText}>Success</Text>
</View>
<View style={styles.legendItem}>
<View style={[styles.legendColor, { backgroundColor: 'orange' }]} />
<Text style={styles.legendText}>Warning</Text>
</View>
<View style={styles.legendItem}>
<View style={[styles.legendColor, { backgroundColor: 'red' }]} />
<Text style={styles.legendText}>Failed</Text>
</View>
</View>
</View>
<View style={styles.row}>
<View style={[styles.card, styles.halfCard]}>
<Text style={styles.cardTitle}>SLA Status</Text>
{renderSLAChart()}
</View>
<TouchableOpacity style={[styles.card, styles.halfCard]} onPress={handleShowJobDetails}>
<Text style={styles.cardTitle}>Job Status 24Hrs</Text>
<Text style={[styles.jobCountText, { color: 'green' }]}>Success: {jobCounts24h.success}</Text>
<Text style={[styles.jobCountText, { color: 'orange' }]}>Warning: {jobCounts24h.warning}</Text>
<Text style={[styles.jobCountText, { color: 'red' }]}>Failed: {jobCounts24h.failed}</Text>
</TouchableOpacity>
</View>
{renderCloudRepositoryStatus()}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.actionButton} onPress={handleShowThreatCenter}>
<Text style={styles.actionButtonText}>Show Threat Center</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.actionButton} onPress={handleShowBillingDashboard}>
<Text style={styles.actionButtonText}>Billing Dashboard</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5F5F5',
},
scrollContent: {
padding: 16,
},
card: {
backgroundColor: '#fff',
padding: 16,
borderRadius: 12,
marginBottom: 16,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
},
halfCard: {
width: '48%',
},
cardTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 12,
color: '#004D40',
},
jobStatusContainer: {
marginBottom: 8,
},
jobStatusText: {
fontSize: 16,
},
jobStatusSubText: {
fontSize: 12,
color: '#666',
},
slaText: {
fontSize: 36,
fontWeight: 'bold',
color: '#004D40',
textAlign: 'center',
},
slaSubtext: {
fontSize: 14,
color: '#666',
textAlign: 'center',
},
spaceContainer: {
marginTop: 8,
},
spaceBar: {
height: 20,
backgroundColor: '#E0E0E0',
borderRadius: 10,
overflow: 'hidden',
},
spaceUsed: {
height: '100%',
backgroundColor: '#004D40',
},
spaceTextContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 8,
},
spaceText: {
fontSize: 14,
},
usedSpace: {
color: 'red',
},
freeSpace: {
color: 'green',
},
actionButton: {
backgroundColor: '#004D40',
padding: 16,
borderRadius: 8,
alignItems: 'center',
flex: 1,
marginHorizontal: 4,
},
actionButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
jobCountText: {
fontSize: 16,
fontWeight: 'bold',
marginBottom: 4,
},
legendContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: 16,
},
legendItem: {
flexDirection: 'row',
alignItems: 'center',
marginHorizontal: 8,
},
legendColor: {
width: 12,
height: 12,
borderRadius: 6,
marginRight: 4,
},
legendText: {
fontSize: 12,
color: '#333',
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 8,
borderRadius: 4,
},
tooltipText: {
color: 'white',
fontSize: 12,
},
slaChartContainer: {
alignItems: 'center',
justifyContent: 'center',
height: 180,
},
slaCenterLabel: {
alignItems: 'center',
justifyContent: 'center',
},
slaPercentage: {
fontSize: 24,
fontWeight: 'bold',
},
slaSubtext: {
fontSize: 12,
color: '#666',
textAlign: 'center',
},
});
export default DashboardScreen;