-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup_frontend.sh
executable file
·1471 lines (1305 loc) · 44.3 KB
/
setup_frontend.sh
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# setup_frontend.sh
# Comprehensive Bash script to automate the setup of a Vite.js and React.js frontend project
# with Framer Motion for animations, Material-UI for high-end UI/UX, and accessibility features.
# Exit immediately if a command exits with a non-zero status
set -e
# Function to display informational messages
function echo_info() {
echo -e "\e[34m[INFO]\e[0m $1"
}
# Function to display success messages
function echo_success() {
echo -e "\e[32m[SUCCESS]\e[0m $1"
}
# Function to display error messages
function echo_error() {
echo -e "\e[31m[ERROR]\e[0m $1"
}
# Check for Node.js installation
if ! command -v node &> /dev/null
then
echo_error "Node.js is not installed. Please install Node.js from https://nodejs.org/"
exit 1
fi
# Check for npm installation
if ! command -v npm &> /dev/null
then
echo_error "npm is not installed. Please install npm."
exit 1
fi
# Variables
PROJECT_NAME="cyber-threat-intel-frontend"
BACKEND_URL="http://localhost:8080" # Modify this if your backend is hosted elsewhere
UI_FRAMEWORK="mui" # Options: mui, bootstrap
# Prompt for UI framework selection
echo "Select a UI Framework:"
echo "1. Material-UI (MUI)"
echo "2. Bootstrap"
read -p "Enter choice [1 or 2]: " UI_CHOICE
if [ "$UI_CHOICE" -eq 1 ]; then
UI_FRAMEWORK="mui"
elif [ "$UI_CHOICE" -eq 2 ]; then
UI_FRAMEWORK="bootstrap"
else
echo_error "Invalid choice. Defaulting to Material-UI (MUI)."
UI_FRAMEWORK="mui"
fi
# Initialize Vite React project
echo_info "Initializing Vite React project..."
# Check if project directory exists
if [ -d "$PROJECT_NAME" ]; then
echo_info "Target directory \"$PROJECT_NAME\" already exists. Removing existing files and continuing..."
rm -rf "$PROJECT_NAME"
fi
# Create the project using Vite
npm create vite@latest $PROJECT_NAME -- --template react
cd $PROJECT_NAME
echo_info "Installing dependencies..."
# Install core dependencies
npm install react-router-dom axios framer-motion
# Install UI framework dependencies
if [ "$UI_FRAMEWORK" = "mui" ]; then
npm install @mui/material @emotion/react @emotion/styled @mui/icons-material
elif [ "$UI_FRAMEWORK" = "bootstrap" ]; then
npm install bootstrap react-bootstrap
fi
# Install form handling libraries
npm install formik yup
# (Optional) Install authentication libraries
# Uncomment if you plan to use JWT decoding
# npm install jwt-decode
# Create Folder Structure
echo_info "Creating folder structure..."
mkdir -p src/api
mkdir -p src/components/ThreatActor
mkdir -p src/components/IncidentLog
mkdir -p src/components/ProtectedRoute
mkdir -p src/context
mkdir -p src/pages
mkdir -p src/services
mkdir -p src/styles
# Initialize API Service
echo_info "Setting up API integration..."
cat > src/api/api.js <<'EOL'
import axios from 'axios';
// Create an Axios instance
const api = axios.create({
baseURL: 'http://localhost:8080', // Replace with your backend URL
});
// Intercept requests to add the Authorization header
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token'); // Ensure token is stored upon login
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});
export default api;
EOL
# Setup Context for Authentication
echo_info "Setting up Authentication Context..."
cat > src/context/AuthContext.jsx <<'EOL'
import React, { createContext, useContext, useState, useEffect } from 'react';
import api from '../api/api';
// Create Auth Context
const AuthContext = createContext();
// Custom hook to use Auth Context
export const useAuth = () => useContext(AuthContext);
// Auth Provider Component
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null); // User object
const [loading, setLoading] = useState(true); // Loading state
// Function to handle login
const login = async (credentials) => {
const response = await api.post('/api/auth/login', credentials);
setUser(response.data.user);
// Store token in localStorage or cookies if provided
localStorage.setItem('token', response.data.token);
};
// Function to handle logout
const logout = () => {
setUser(null);
localStorage.removeItem('token');
};
// Fetch user on component mount
useEffect(() => {
const fetchUser = async () => {
try {
const token = localStorage.getItem('token');
if (token) {
// Set token in axios headers
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
const response = await api.get('/api/auth/me');
setUser(response.data);
}
} catch (error) {
console.error(error);
logout();
} finally {
setLoading(false);
}
};
fetchUser();
}, []);
const value = {
user,
loading,
login,
logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
EOL
# Setup ProtectedRoute Component
echo_info "Setting up ProtectedRoute component..."
cat > src/components/ProtectedRoute/ProtectedRoute.jsx <<'EOL'
import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
const ProtectedRoute = ({ children }) => {
const { user, loading } = useAuth();
if (loading) return <div>Loading...</div>;
return user ? children : <Navigate to="/login" />;
};
export default ProtectedRoute;
EOL
# Setup Framer Motion Wrapper (Optional for Consistent Animations)
echo_info "Setting up Framer Motion wrapper for consistent animations..."
cat > src/components/MotionWrapper.jsx <<'EOL'
import React from 'react';
import { motion } from 'framer-motion';
const MotionWrapper = ({ children, variants, initial, animate, exit }) => {
return (
<motion.div
variants={variants}
initial={initial}
animate={animate}
exit={exit}
style={{ width: '100%' }}
>
{children}
</motion.div>
);
};
export default MotionWrapper;
EOL
# Setup ThreatActorService
echo_info "Setting up ThreatActorService..."
cat > src/services/ThreatActorService.js <<'EOL'
import api from '../api/api';
const ThreatActorService = {
getAll: () => api.get('/api/threatactors'),
getById: (id) => api.get(`/api/threatactors/${id}`),
create: (data) => api.post('/api/threatactors', data),
update: (id, data) => api.put(`/api/threatactors/${id}`, data),
delete: (id) => api.delete(`/api/threatactors/${id}`),
};
export default ThreatActorService;
EOL
# Setup IncidentLogService
echo_info "Setting up IncidentLogService..."
cat > src/services/IncidentLogService.js <<'EOL'
import api from '../api/api';
const IncidentLogService = {
getAll: () => api.get('/api/incidentlogs'),
getById: (id) => api.get(`/api/incidentlogs/${id}`),
create: (data) => api.post('/api/incidentlogs', data),
update: (id, data) => api.put(`/api/incidentlogs/${id}`, data),
delete: (id) => api.delete(`/api/incidentlogs/${id}`),
};
export default IncidentLogService;
EOL
# Setup ThreatActorList Component with Framer Motion
echo_info "Setting up ThreatActorList component with animations..."
cat > src/components/ThreatActor/ThreatActorList.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import ThreatActorService from '../../services/ThreatActorService';
import { Link } from 'react-router-dom';
import { Table, Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
const tableVariants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
};
const ThreatActorList = () => {
const [threatActors, setThreatActors] = useState([]);
useEffect(() => {
fetchThreatActors();
}, []);
const fetchThreatActors = async () => {
try {
const response = await ThreatActorService.getAll();
setThreatActors(response.data);
} catch (error) {
console.error('Error fetching Threat Actors:', error);
}
};
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this Threat Actor?')) {
try {
await ThreatActorService.delete(id);
setThreatActors(threatActors.filter((actor) => actor.actorId !== id));
} catch (error) {
console.error('Error deleting Threat Actor:', error);
}
}
};
return (
<Container>
<Box mt={5}>
<Typography variant="h4" gutterBottom>
Threat Actors
</Typography>
<Button
variant="contained"
color="primary"
component={Link}
to="/threatactors/create"
style={{ marginBottom: '20px' }}
>
Add Threat Actor
</Button>
<motion.div
variants={tableVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3}>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Origin Country</th>
<th>First Observed</th>
<th>Last Activity</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{threatActors.map((actor) => (
<tr key={actor.actorId}>
<td>{actor.name}</td>
<td>{actor.type}</td>
<td>{actor.originCountry}</td>
<td>{new Date(actor.firstObserved).toLocaleDateString()}</td>
<td>{new Date(actor.lastActivity).toLocaleDateString()}</td>
<td>
<Button
component={Link}
to={`/threatactors/${actor.actorId}`}
variant="outlined"
color="primary"
style={{ marginRight: '10px' }}
aria-label={`View details of ${actor.name}`}
>
View
</Button>
<Button
component={Link}
to={`/threatactors/edit/${actor.actorId}`}
variant="outlined"
color="secondary"
style={{ marginRight: '10px' }}
aria-label={`Edit ${actor.name}`}
>
Edit
</Button>
<Button
onClick={() => handleDelete(actor.actorId)}
variant="outlined"
color="error"
aria-label={`Delete ${actor.name}`}
>
Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table>
</Paper>
</motion.div>
</Box>
</Container>
);
};
export default ThreatActorList;
EOL
# Setup ThreatActorDetail Component with Framer Motion
echo_info "Setting up ThreatActorDetail component with animations..."
cat > src/components/ThreatActor/ThreatActorDetail.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import ThreatActorService from '../../services/ThreatActorService';
import { Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
const detailVariants = {
hidden: { opacity: 0, x: -50 },
visible: { opacity: 1, x: 0 },
};
const ThreatActorDetail = () => {
const { id } = useParams();
const [threatActor, setThreatActor] = useState(null);
useEffect(() => {
fetchThreatActor();
// eslint-disable-next-line
}, []);
const fetchThreatActor = async () => {
try {
const response = await ThreatActorService.getById(id);
setThreatActor(response.data);
} catch (error) {
console.error('Error fetching Threat Actor:', error);
}
};
if (!threatActor) return <div>Loading...</div>;
return (
<Container>
<Box mt={5}>
<motion.div
variants={detailVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3} style={{ padding: '20px' }}>
<Typography variant="h4" gutterBottom>
Threat Actor Details
</Typography>
<Typography variant="body1"><strong>Name:</strong> {threatActor.name}</Typography>
<Typography variant="body1"><strong>Type:</strong> {threatActor.type}</Typography>
<Typography variant="body1"><strong>Description:</strong> {threatActor.description}</Typography>
<Typography variant="body1"><strong>Origin Country:</strong> {threatActor.originCountry}</Typography>
<Typography variant="body1"><strong>First Observed:</strong> {new Date(threatActor.firstObserved).toLocaleDateString()}</Typography>
<Typography variant="body1"><strong>Last Activity:</strong> {new Date(threatActor.lastActivity).toLocaleDateString()}</Typography>
<Box mt={3}>
<Button
component={Link}
to={`/threatactors/edit/${threatActor.actorId}`}
variant="contained"
color="secondary"
style={{ marginRight: '10px' }}
aria-label={`Edit ${threatActor.name}`}
>
Edit
</Button>
<Button
component={Link}
to="/threatactors"
variant="contained"
color="primary"
aria-label="Back to Threat Actors List"
>
Back to List
</Button>
</Box>
</Paper>
</motion.div>
</Box>
</Container>
);
};
export default ThreatActorDetail;
EOL
# Setup ThreatActorForm Component with Framer Motion
echo_info "Setting up ThreatActorForm component with animations..."
cat > src/components/ThreatActor/ThreatActorForm.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import ThreatActorService from '../../services/ThreatActorService';
import { TextField, Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
import { useFormik } from 'formik';
import * as Yup from 'yup';
const formVariants = {
hidden: { opacity: 0, scale: 0.95 },
visible: { opacity: 1, scale: 1 },
};
const ThreatActorForm = () => {
const { id } = useParams();
const navigate = useNavigate();
const isEditMode = Boolean(id);
const [initialValues, setInitialValues] = useState({
name: '',
type: '',
description: '',
originCountry: '',
firstObserved: '',
lastActivity: '',
// Add other fields as necessary
});
const [error, setError] = useState('');
useEffect(() => {
if (isEditMode) {
fetchThreatActor();
}
// eslint-disable-next-line
}, [id]);
const fetchThreatActor = async () => {
try {
const response = await ThreatActorService.getById(id);
const data = response.data;
setInitialValues({
name: data.name || '',
type: data.type || '',
description: data.description || '',
originCountry: data.originCountry || '',
firstObserved: data.firstObserved ? data.firstObserved.substring(0, 10) : '',
lastActivity: data.lastActivity ? data.lastActivity.substring(0, 10) : '',
// Initialize other fields as necessary
});
} catch (error) {
console.error('Error fetching Threat Actor:', error);
setError('Failed to load Threat Actor data.');
}
};
const validationSchema = Yup.object({
name: Yup.string().required('Name is required'),
type: Yup.string().required('Type is required'),
description: Yup.string().required('Description is required'),
originCountry: Yup.string().required('Origin Country is required'),
firstObserved: Yup.date().required('First Observed date is required'),
lastActivity: Yup.date().required('Last Activity date is required'),
// Add other validations as necessary
});
const formik = useFormik({
enableReinitialize: true,
initialValues: initialValues,
validationSchema: validationSchema,
onSubmit: async (values) => {
try {
if (isEditMode) {
await ThreatActorService.update(id, values);
} else {
await ThreatActorService.create(values);
}
navigate('/threatactors');
} catch (error) {
console.error('Error saving Threat Actor:', error);
setError('Failed to save Threat Actor.');
}
},
});
return (
<Container>
<Box mt={5}>
<motion.div
variants={formVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3} style={{ padding: '20px' }}>
<Typography variant="h4" gutterBottom>
{isEditMode ? 'Edit Threat Actor' : 'Add Threat Actor'}
</Typography>
{error && <Typography color="error" variant="body1">{error}</Typography>}
<form onSubmit={formik.handleSubmit}>
<TextField
label="Name"
name="name"
value={formik.values.name}
onChange={formik.handleChange}
required
fullWidth
margin="normal"
aria-label="Threat Actor Name"
error={formik.touched.name && Boolean(formik.errors.name)}
helperText={formik.touched.name && formik.errors.name}
/>
<TextField
label="Type"
name="type"
value={formik.values.type}
onChange={formik.handleChange}
required
fullWidth
margin="normal"
aria-label="Threat Actor Type"
error={formik.touched.type && Boolean(formik.errors.type)}
helperText={formik.touched.type && formik.errors.type}
/>
<TextField
label="Description"
name="description"
value={formik.values.description}
onChange={formik.handleChange}
required
multiline
rows={4}
fullWidth
margin="normal"
aria-label="Threat Actor Description"
error={formik.touched.description && Boolean(formik.errors.description)}
helperText={formik.touched.description && formik.errors.description}
/>
<TextField
label="Origin Country"
name="originCountry"
value={formik.values.originCountry}
onChange={formik.handleChange}
required
fullWidth
margin="normal"
aria-label="Origin Country"
error={formik.touched.originCountry && Boolean(formik.errors.originCountry)}
helperText={formik.touched.originCountry && formik.errors.originCountry}
/>
<TextField
label="First Observed"
name="firstObserved"
type="date"
value={formik.values.firstObserved}
onChange={formik.handleChange}
InputLabelProps={{ shrink: true }}
required
fullWidth
margin="normal"
aria-label="First Observed Date"
error={formik.touched.firstObserved && Boolean(formik.errors.firstObserved)}
helperText={formik.touched.firstObserved && formik.errors.firstObserved}
/>
<TextField
label="Last Activity"
name="lastActivity"
type="date"
value={formik.values.lastActivity}
onChange={formik.handleChange}
InputLabelProps={{ shrink: true }}
required
fullWidth
margin="normal"
aria-label="Last Activity Date"
error={formik.touched.lastActivity && Boolean(formik.errors.lastActivity)}
helperText={formik.touched.lastActivity && formik.errors.lastActivity}
/>
{/* Add additional fields as necessary */}
<Box mt={3}>
<Button
type="submit"
variant="contained"
color="primary"
style={{ marginRight: '10px' }}
aria-label={isEditMode ? 'Update Threat Actor' : 'Create Threat Actor'}
>
{isEditMode ? 'Update' : 'Create'}
</Button>
<Button
variant="outlined"
color="secondary"
component={Link}
to="/threatactors"
aria-label="Cancel and go back to Threat Actors List"
>
Cancel
</Button>
</Box>
</form>
</Paper>
</motion.div>
</Box>
</Container>
);
};
export default ThreatActorForm;
EOL
# Setup IncidentLogList Component with Framer Motion
echo_info "Setting up IncidentLogList component with animations..."
cat > src/components/IncidentLog/IncidentLogList.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import IncidentLogService from '../../services/IncidentLogService';
import { Link } from 'react-router-dom';
import { Table, Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
const tableVariants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
};
const IncidentLogList = () => {
const [incidentLogs, setIncidentLogs] = useState([]);
useEffect(() => {
fetchIncidentLogs();
}, []);
const fetchIncidentLogs = async () => {
try {
const response = await IncidentLogService.getAll();
setIncidentLogs(response.data);
} catch (error) {
console.error('Error fetching Incident Logs:', error);
}
};
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this Incident Log?')) {
try {
await IncidentLogService.delete(id);
setIncidentLogs(incidentLogs.filter((log) => log.logId !== id));
} catch (error) {
console.error('Error deleting Incident Log:', error);
}
}
};
return (
<Container>
<Box mt={5}>
<Typography variant="h4" gutterBottom>
Incident Logs
</Typography>
<Button
variant="contained"
color="primary"
component={Link}
to="/incidentlogs/create"
style={{ marginBottom: '20px' }}
>
Add Incident Log
</Button>
<motion.div
variants={tableVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3}>
<Table>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{incidentLogs.map((log) => (
<tr key={log.logId}>
<td>{log.title}</td>
<td>{log.description}</td>
<td>{new Date(log.date).toLocaleDateString()}</td>
<td>
<Button
component={Link}
to={`/incidentlogs/${log.logId}`}
variant="outlined"
color="primary"
style={{ marginRight: '10px' }}
aria-label={`View details of ${log.title}`}
>
View
</Button>
<Button
component={Link}
to={`/incidentlogs/edit/${log.logId}`}
variant="outlined"
color="secondary"
style={{ marginRight: '10px' }}
aria-label={`Edit ${log.title}`}
>
Edit
</Button>
<Button
onClick={() => handleDelete(log.logId)}
variant="outlined"
color="error"
aria-label={`Delete ${log.title}`}
>
Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table>
</Paper>
</motion.div>
</Box>
</Container>
);
};
export default IncidentLogList;
EOL
# Setup IncidentLogDetail Component with Framer Motion
echo_info "Setting up IncidentLogDetail component with animations..."
cat > src/components/IncidentLog/IncidentLogDetail.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import IncidentLogService from '../../services/IncidentLogService';
import { Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
const detailVariants = {
hidden: { opacity: 0, x: -50 },
visible: { opacity: 1, x: 0 },
};
const IncidentLogDetail = () => {
const { id } = useParams();
const [incidentLog, setIncidentLog] = useState(null);
useEffect(() => {
fetchIncidentLog();
// eslint-disable-next-line
}, []);
const fetchIncidentLog = async () => {
try {
const response = await IncidentLogService.getById(id);
setIncidentLog(response.data);
} catch (error) {
console.error('Error fetching Incident Log:', error);
}
};
if (!incidentLog) return <div>Loading...</div>;
return (
<Container>
<Box mt={5}>
<motion.div
variants={detailVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3} style={{ padding: '20px' }}>
<Typography variant="h4" gutterBottom>
Incident Log Details
</Typography>
<Typography variant="body1"><strong>Title:</strong> {incidentLog.title}</Typography>
<Typography variant="body1"><strong>Description:</strong> {incidentLog.description}</Typography>
<Typography variant="body1"><strong>Date:</strong> {new Date(incidentLog.date).toLocaleDateString()}</Typography>
<Box mt={3}>
<Button
component={Link}
to={`/incidentlogs/edit/${incidentLog.logId}`}
variant="contained"
color="secondary"
style={{ marginRight: '10px' }}
aria-label={`Edit ${incidentLog.title}`}
>
Edit
</Button>
<Button
component={Link}
to="/incidentlogs"
variant="contained"
color="primary"
aria-label="Back to Incident Logs List"
>
Back to List
</Button>
</Box>
</Paper>
</motion.div>
</Box>
</Container>
);
};
export default IncidentLogDetail;
EOL
# Setup IncidentLogForm Component with Framer Motion
echo_info "Setting up IncidentLogForm component with animations..."
cat > src/components/IncidentLog/IncidentLogForm.jsx <<'EOL'
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import IncidentLogService from '../../services/IncidentLogService';
import { TextField, Button, Container, Typography, Box, Paper } from '@mui/material';
import { motion } from 'framer-motion';
import { useFormik } from 'formik';
import * as Yup from 'yup';
const formVariants = {
hidden: { opacity: 0, scale: 0.95 },
visible: { opacity: 1, scale: 1 },
};
const IncidentLogForm = () => {
const { id } = useParams();
const navigate = useNavigate();
const isEditMode = Boolean(id);
const [initialValues, setInitialValues] = useState({
title: '',
description: '',
date: '',
// Add other fields as necessary
});
const [error, setError] = useState('');
useEffect(() => {
if (isEditMode) {
fetchIncidentLog();
}
// eslint-disable-next-line
}, [id]);
const fetchIncidentLog = async () => {
try {
const response = await IncidentLogService.getById(id);
const data = response.data;
setInitialValues({
title: data.title || '',
description: data.description || '',
date: data.date ? data.date.substring(0, 10) : '',
// Initialize other fields as necessary
});
} catch (error) {
console.error('Error fetching Incident Log:', error);
setError('Failed to load Incident Log data.');
}
};
const validationSchema = Yup.object({
title: Yup.string().required('Title is required'),
description: Yup.string().required('Description is required'),
date: Yup.date().required('Date is required'),
// Add other validations as necessary
});
const formik = useFormik({
enableReinitialize: true,
initialValues: initialValues,
validationSchema: validationSchema,
onSubmit: async (values) => {
try {
if (isEditMode) {
await IncidentLogService.update(id, values);
} else {
await IncidentLogService.create(values);
}
navigate('/incidentlogs');
} catch (error) {
console.error('Error saving Incident Log:', error);
setError('Failed to save Incident Log.');
}
},
});
return (
<Container>
<Box mt={5}>
<motion.div
variants={formVariants}
initial="hidden"
animate="visible"
transition={{ duration: 0.5 }}
>
<Paper elevation={3} style={{ padding: '20px' }}>
<Typography variant="h4" gutterBottom>
{isEditMode ? 'Edit Incident Log' : 'Add Incident Log'}
</Typography>
{error && <Typography color="error" variant="body1">{error}</Typography>}
<form onSubmit={formik.handleSubmit}>
<TextField
label="Title"
name="title"
value={formik.values.title}