error-handling #1

Merged
stwhite merged 24 commits from error-handling into main 2024-10-30 15:19:49 +00:00
7 changed files with 626 additions and 610 deletions
Showing only changes of commit 2e598968ac - Show all commits

View File

@ -1,114 +1,121 @@
// src/components/Admin.js
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import './Admin.css';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
import './Admin.css'; // Import the CSS file
import { import {
Typography, Typography,
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableContainer, TableContainer,
TableHead, TableHead,
TableRow, TableRow,
Paper, Paper,
Button, Button,
Alert, Alert,
Container, Container,
Box, Box,
TextField, TextField,
Tab CircularProgress
} from '@mui/material'; } from '@mui/material';
export default function Admin() {
const [users, setUsers] = useState([]);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const fileInputRef = useRef(null);
export default function Admin() { const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall();
const [users, setUsers] = useState([]); const { execute: createUser, loading: creatingUser, error: createError } = useApiCall();
const [username, setUsername] = useState(''); const { execute: deleteUser, loading: deletingUser, error: deleteError } = useApiCall();
const [email, setEmail] = useState(''); const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall();
const [password, setPassword] = useState(''); const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall();
const navigate = useNavigate();
const fileInputRef = useRef(null);
useEffect(() => { useEffect(() => {
fetchUsers(); const getUsers = async () => {
}, []);
const fetchUsers = async () => {
try { try {
const response = await api.admin.getUsers(localStorage.getItem('token')); const response = await fetchUsers(() =>
api.admin.getUsers(localStorage.getItem('token'))
);
setUsers(response.data); setUsers(response.data);
} catch (error) { } catch (err) {}
console.error('Error fetching users:', error);
}
}; };
getUsers();
}, []);
const handleCreateUser = async (e) => { const handleCreateUser = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
const response = await api.admin.createUser(localStorage.getItem('token'), { const response = await createUser(() =>
username, api.admin.createUser(
password, localStorage.getItem('token'),
email { username, password, email }
}); )
setUsers([...users, response.data]); );
setUsername(''); setUsers([...users, response.data]);
setPassword(''); setUsername('');
setEmail(''); setPassword('');
} catch (error) { setEmail('');
console.error(error); } catch (err) {}
} };
};
const handleDeleteUser = async (id) => { const handleDeleteUser = async (id) => {
try { try {
await api.admin.deleteUser(localStorage.getItem('token'), id); await deleteUser(() =>
setUsers(users.filter(user => user.id !== id)); api.admin.deleteUser(localStorage.getItem('token'), id)
fetchUsers(); );
} catch (error) { setUsers(users.filter(user => user.id !== id));
console.error(error); } catch (err) {}
} };
};
const handleBackupDatabase = async () => { const handleBackupDatabase = async () => {
try { try {
const response = await api.admin.backupDb(localStorage.getItem('token')); const response = await backupDB(() =>
const blob = new Blob([response.data], { type: 'application/x-sqlite3' }); api.admin.backupDB(localStorage.getItem('token'))
const url = URL.createObjectURL(blob); );
const a = document.createElement('a'); const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
a.href = url; const url = URL.createObjectURL(blob);
a.download = 'database.db'; const a = document.createElement('a');
a.click(); a.href = url;
} catch (error) { a.download = 'database.db';
console.error(error); a.click();
} } catch (err) {}
}; };
const handleRestoreDatabase = async (e) => { const handleRestoreDatabase = async (e) => {
e.preventDefault(); e.preventDefault();
try { if (!fileInputRef.current?.files?.[0]) return;
const file = fileInputRef.current.files[0];
const formData = new FormData();
formData.append('database', file);
const response = await api.admin.restoreDb(localStorage.getItem('token'), formData); try {
const formData = new FormData();
if (response.status === 200) { formData.append('database', fileInputRef.current.files[0]);
alert('Database restored successfully');
navigate('/admin');
}
} catch (error) {
console.error(error);
}
};
await restoreDB(() =>
api.admin.restoreDB(localStorage.getItem('token'), formData)
);
alert('Database restored successfully');
navigate('/admin');
} catch (err) {}
};
return ( return (
<Container maxWidth="md"> <Container maxWidth="md">
<Typography variant="h4" gutterBottom> <Typography variant="h4" gutterBottom>
Admin Admin Dashboard
</Typography> </Typography>
{(usersError || createError || deleteError || backupError || restoreError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{usersError?.message || createError?.message || deleteError?.message ||
backupError?.message || restoreError?.message}
</Alert>
)}
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}> <Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
<Typography variant="h6" gutterBottom> <Typography variant="h6" gutterBottom>
Add New User Add New User
@ -119,6 +126,7 @@ import {
value={username} value={username}
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
sx={{ mr: 2 }} sx={{ mr: 2 }}
disabled={creatingUser}
/> />
<TextField <TextField
label="Password" label="Password"
@ -127,6 +135,7 @@ import {
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
sx={{ mr: 2 }} sx={{ mr: 2 }}
disabled={creatingUser}
/> />
<TextField <TextField
label="Email" label="Email"
@ -134,60 +143,71 @@ import {
value={email} value={email}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
sx={{ mr: 2 }} sx={{ mr: 2 }}
disabled={creatingUser}
/> />
<Button type="submit" sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary"> <Button
Add User type="submit"
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
disabled={creatingUser}
>
{creatingUser ? <CircularProgress size={24} /> : 'Add User'}
</Button> </Button>
</Box> </Box>
<TableContainer component={Paper}> {loadingUsers ? (
<Table> <CircularProgress />
<TableHead> ) : (
<TableRow> <TableContainer component={Paper}>
<TableCell>ID</TableCell> <Table>
<TableCell>Username</TableCell> <TableHead>
<TableCell>Email</TableCell> <TableRow>
<TableCell>Actions</TableCell> <TableCell>ID</TableCell>
</TableRow> <TableCell>Username</TableCell>
</TableHead> <TableCell>Email</TableCell>
<TableBody> <TableCell>Actions</TableCell>
{users.map(user => (
<TableRow key={user.ID}>
<TableCell style={{ width: '30px' }}>{user.ID}</TableCell>
<TableCell style={{ width: '100px'}}>{user.username}</TableCell>
<TableCell style={{ width: '300px'}}>{user.email}</TableCell>
<TableCell>
<Button
variant="contained"
color="error"
onClick={() => handleDeleteUser(user.ID)}
>
Delete User
</Button>
</TableCell>
</TableRow> </TableRow>
))} </TableHead>
</TableBody> <TableBody>
</Table> {users.map(user => (
</TableContainer> <TableRow key={user.ID}>
<TableCell>{user.ID}</TableCell>
<TableCell>{user.username}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
<Button
variant="contained"
color="error"
onClick={() => handleDeleteUser(user.ID)}
disabled={deletingUser}
>
{deletingUser ? <CircularProgress size={24} /> : 'Delete User'}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
<Box sx={{ mt: 4 }}> <Box sx={{ mt: 4 }}>
<Button <Button
variant="contained" variant="contained"
color="primary"
onClick={handleBackupDatabase} onClick={handleBackupDatabase}
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
disabled={backingUp}
> >
Backup Database {backingUp ? <CircularProgress size={24} /> : 'Backup Database'}
</Button> </Button>
<Button <Button
variant="contained" variant="contained"
color="secondary"
component="label" component="label"
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
disabled={restoring}
> >
Restore Database {restoring ? <CircularProgress size={24} /> : 'Restore Database'}
<input <input
type="file" type="file"
hidden hidden

View File

@ -1,85 +1,122 @@
// src/components/Boxes.js
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Container, Button, TextField, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material'; import {
Container,
Button,
TextField,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Alert,
CircularProgress
} from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material'; import { Delete as DeleteIcon } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom'; // Import Link from react-router-dom import { Link as RouterLink } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
export default function Boxes({ token }) { export default function Boxes({ token }) {
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [newBoxName, setNewBoxName] = useState(''); const [newBoxName, setNewBoxName] = useState('');
useEffect(() => { const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
fetchBoxes(); const { execute: createBox, loading: creatingBox, error: createError } = useApiCall();
}, [token]); const { execute: deleteBox, loading: deletingBox, error: deleteError } = useApiCall();
const fetchBoxes = async () => { useEffect(() => {
try { const getBoxes = async () => {
const response = await api.boxes.getAll(token); try {
setBoxes(response.data); const response = await fetchBoxes(() =>
} catch (error) { api.boxes.getAll(token)
console.error('Error fetching boxes:', error); );
} setBoxes(response.data);
}; } catch (err) {}
};
getBoxes();
}, [token]); // Remove fetchBoxes from dependencies
const handleCreateBox = async () => { const handleCreateBox = async () => {
if (!newBoxName.trim()) return;
try { try {
const response = await api.boxes.create(token, { name: newBoxName }); const response = await createBox(() =>
api.boxes.create(token, { name: newBoxName })
);
setBoxes([...boxes, response.data]); setBoxes([...boxes, response.data]);
setNewBoxName(''); setNewBoxName('');
} catch (error) { } catch (err) {}
console.error('Error creating box:', error);
}
}; };
const handleDeleteBox = async (id) => { const handleDeleteBox = async (id) => {
try { try {
await api.boxes.delete(token, id); await deleteBox(() =>
api.boxes.delete(token, id)
);
setBoxes(boxes.filter(box => box.ID !== id)); setBoxes(boxes.filter(box => box.ID !== id));
} catch (error) { } catch (err) {}
console.error('Error deleting box:', error);
}
}; };
return ( return (
<Container> <Container>
{(boxesError || createError || deleteError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{boxesError?.message || createError?.message || deleteError?.message}
</Alert>
)}
<TableContainer> {loadingBoxes ? (
<Table size="small"> <CircularProgress />
<TableHead> ) : (
<TableRow> <TableContainer>
<TableCell>Box Name</TableCell> <Table size="small">
<TableCell>Actions</TableCell> <TableHead>
</TableRow> <TableRow>
</TableHead> <TableCell>Box Name</TableCell>
<TableBody> <TableCell>Actions</TableCell>
{boxes.map((box) => (
<TableRow key={box.ID}>
<TableCell>
<RouterLink to={`/api/v1/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}>
{box.name}
</RouterLink>
</TableCell>
<TableCell>
<Button onClick={() => handleDeleteBox(box.ID)} startIcon={<DeleteIcon />}>
Delete
</Button>
</TableCell>
</TableRow> </TableRow>
))} </TableHead>
</TableBody> <TableBody>
</Table> {boxes.map((box) => (
</TableContainer> <TableRow key={box.ID}>
<TableCell>
<RouterLink to={`/api/v1/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}>
{box.name}
</RouterLink>
</TableCell>
<TableCell>
<Button
onClick={() => handleDeleteBox(box.ID)}
startIcon={<DeleteIcon />}
disabled={deletingBox}
>
{deletingBox ? <CircularProgress size={20} /> : 'Delete'}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
<TextField <TextField
label="New Box" label="New Box"
variant="outlined" variant="outlined"
fullWidth fullWidth
value={newBoxName} value={newBoxName}
onChange={(e) => setNewBoxName(e.target.value)} onChange={(e) => setNewBoxName(e.target.value)}
disabled={creatingBox}
/> />
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleCreateBox}> <Button
Add Box sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={handleCreateBox}
disabled={creatingBox || !newBoxName.trim()}
>
{creatingBox ? <CircularProgress size={24} /> : 'Add Box'}
</Button> </Button>
</Container> </Container>
); );

View File

@ -1,141 +1,123 @@
// src/components/ItemDetails.js import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useRef, useCallback } from 'react'; import { TextField, Button, Container, Avatar, Tooltip, Alert, CircularProgress } from '@mui/material';
import { TextField, Button, Container, Avatar, Tooltip } from '@mui/material';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
export default function ItemDetails({ item, token, onSave, onClose, boxId }) { export default function ItemDetails({ item, token, onSave, onClose }) {
const [name, setName] = useState(item.name); const [name, setName] = useState(item.name);
const [description, setDescription] = useState(item.description); const [description, setDescription] = useState(item.description);
const [imagePath, setImagePath] = useState(item.image_path || ''); const [imagePath, setImagePath] = useState(item.image_path || '');
const [imageSrc, setImageSrc] = useState('/images/default.jpg'); const [imageSrc, setImageSrc] = useState('/images/default.jpg');
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
const [imageOverlayVisible, setImageOverlayVisible] = useState(false); const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
const [boxName, setBoxName] = useState('');
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [selectedBoxId, setSelectedBoxId] = useState(item.box_id); const [selectedBoxId, setSelectedBoxId] = useState(item.box_id);
const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
const { execute: updateItem, loading: savingItem, error: saveError } = useApiCall();
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
useEffect(() => { useEffect(() => {
const fetchBoxes = async () => { const getBoxes = async () => {
try { try {
const response = await api.boxes.getAll(token); const response = await fetchBoxes(() => api.boxes.getAll(token));
setBoxes(response.data); setBoxes(response.data);
} catch (error) { } catch (err) {}
console.error('Error fetching boxes:', error);
}
}; };
fetchBoxes(); getBoxes();
}, [token]); }, [token]);
const handleBoxChange = (event) => {
const newBoxId = event.target.value;
setSelectedBoxId(newBoxId);
};
useEffect(() => { useEffect(() => {
const getBoxDetails = async (boxId) => { const loadImage = async () => {
try { setLoading(true);
const boxIdNumber = +boxId; setError(null);
if (isNaN(boxIdNumber)) {
console.error('Invalid boxId:', boxId);
return;
}
const response = await api.boxes.getAll(token);
const box = response.data.find(b => b.ID === boxIdNumber);
if (box) {
setBoxName(box.name);
}
} catch (error) {
console.error('Error fetching box details:', error);
}
};
if (selectedBoxId !== item.box_id) {
getBoxDetails(selectedBoxId);
} else if (item.box_id) {
getBoxDetails(item.box_id);
}
}, [selectedBoxId, token, item.box_id]);
useEffect(() => {
const fetchItemImage = async () => {
try { try {
const response = await api.items.getImage(token, item.ID); const response = await api.items.getImage(token, item.ID);
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => setImageSrc(reader.result); reader.onload = () => {
setImageSrc(reader.result);
setLoading(false);
};
reader.readAsDataURL(response.data); reader.readAsDataURL(response.data);
} catch (error) { } catch (err) {
setImageSrc('/default.jpg'); setImageSrc('/default.jpg');
setError(err);
setLoading(false);
} }
}; };
fetchItemImage(); loadImage();
}, [item.ID, token]); }, [item.ID, token]);
const handleImageUpload = useCallback(async () => { const handleImageUpload = async () => {
if (!fileInputRef.current.files[0]) return; if (!fileInputRef.current?.files?.[0]) return null;
const formData = new FormData(); const formData = new FormData();
formData.append('image', fileInputRef.current.files[0]); formData.append('image', fileInputRef.current.files[0]);
try { try {
const response = await api.items.uploadImage(token, item.ID, formData); const response = await uploadImage(() =>
api.items.uploadImage(token, item.ID, formData)
);
return response.data.imagePath; return response.data.imagePath;
} catch (error) { } catch (err) {
console.error('Image upload failed:', error); return null;
} }
}, [item.ID, token]); };
const handleSave = useCallback(async () => { const handleSave = async () => {
let imagePath; if (fileInputRef.current?.files?.[0]) {
if (fileInputRef.current.files[0]) { await handleImageUpload();
imagePath = await handleImageUpload();
} }
try { try {
await api.items.update(token, item.ID, { await updateItem(() => api.items.update(token, item.ID, {
name, name,
description, description,
box_id: +selectedBoxId, box_id: +selectedBoxId,
}); }));
onSave(); onSave();
} catch (error) { } catch (err) {}
console.error('Item update failed:', error);
}
}, [item.ID, name, description, selectedBoxId, token, onSave, handleImageUpload]);
const handleImageError = (e) => {
e.target.src = '/images/default.jpg';
}; };
const handleAvatarClick = () => { const handleBoxChange = (event) => {
setImageOverlayVisible(true); setSelectedBoxId(event.target.value);
};
const handleCloseOverlay = () => {
setImageOverlayVisible(false);
}; };
return ( return (
<Container> <Container>
<h3>Edit Item: {item.name}</h3> <h3>Edit Item: {item.name}</h3>
<Tooltip title="Click to enlarge"> {(error || boxesError || saveError || uploadError) && (
<Avatar <Alert severity="error" sx={{ mb: 2 }}>
src={imageSrc} {error?.message || boxesError?.message || saveError?.message || uploadError?.message}
alt={name} </Alert>
onError={handleImageError} )}
sx={{ width: 200, height: 200, marginBottom: '16px' }}
onClick={handleAvatarClick} {loading ? (
/> <CircularProgress />
</Tooltip> ) : (
<Tooltip title="Click to enlarge">
<Avatar
src={imageSrc}
alt={name}
sx={{ width: 200, height: 200, marginBottom: '16px' }}
onClick={() => setImageOverlayVisible(true)}
/>
</Tooltip>
)}
{imageOverlayVisible && ( {imageOverlayVisible && (
<div className="image-overlay"> <div className="image-overlay">
<img src={imageSrc} alt={name} /> <img src={imageSrc} alt={name} />
<button className="close-button" onClick={handleCloseOverlay}> <button className="close-button" onClick={() => setImageOverlayVisible(false)}>
Close Close
</button> </button>
</div> </div>
)} )}
<TextField <TextField
label="Item Name" label="Item Name"
variant="outlined" variant="outlined"
@ -143,6 +125,7 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
margin="normal" margin="normal"
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
disabled={savingItem}
/> />
<TextField <TextField
label="Item Description" label="Item Description"
@ -151,50 +134,62 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
margin="normal" margin="normal"
value={description} value={description}
onChange={(e) => setDescription(e.target.value)} onChange={(e) => setDescription(e.target.value)}
disabled={savingItem}
/> />
<TextField
label="Item Image Path" {loadingBoxes ? (
variant="outlined" <CircularProgress size={24} />
fullWidth ) : (
margin="normal" <select
value={imagePath} value={selectedBoxId}
onChange={(e) => setImagePath(e.target.value)} onChange={handleBoxChange}
sx={{ display: 'none' }} disabled={savingItem}
/> >
<input <option value="">No box</option>
type="file" {boxes.map((box) => (
accept="image/*" <option key={box.ID} value={box.ID}>
ref={fileInputRef} {box.name}
style={{ display: 'none' }} </option>
id="editItemImageUpload" ))}
/> </select>
<select value={selectedBoxId} onChange={handleBoxChange}> )}
<option value="">No box</option>
{boxes.map((box) => ( <br />
<option key={box.ID} value={box.ID}> <br />
{box.name}
</option> <Button
))} sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
</select> variant="contained"
<br/> component="label"
<br/> disabled={uploadingImage || savingItem}
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" component="label" htmlFor="editItemImageUpload"> >
Upload Image {uploadingImage ? <CircularProgress size={24} /> : 'Upload Image'}
<input <input
type="file" type="file"
accept="image/*" accept="image/*"
id="image-upload" ref={fileInputRef}
style={{ display: 'none' }} style={{ display: 'none' }}
onChange={(e) => { onChange={(e) => setImagePath(e.target.files[0]?.name || '')}
setImagePath(e.target.files[0].name);
}}
/> />
</Button> </Button>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleSave}> <Button
Save Changes sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={handleSave}
disabled={savingItem}
>
{savingItem ? <CircularProgress size={24} /> : 'Save Changes'}
</Button>
<Button
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={onClose}
disabled={savingItem}
>
Close
</Button> </Button>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={onClose}>Close</Button>
</Container> </Container>
); );
} }

View File

@ -1,19 +1,9 @@
import React, { useEffect, useState, useCallback, useRef } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { import {
Container, Container,
List,
ListItem,
ListItemText,
TextField,
Button, Button,
IconButton, IconButton,
Typography, TextField,
Avatar,
ListItemAvatar,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TableContainer, TableContainer,
Table, Table,
TableHead, TableHead,
@ -21,213 +11,52 @@ import {
TableCell, TableCell,
TableBody, TableBody,
Box, Box,
Tooltip Tooltip,
Avatar,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Alert,
CircularProgress
} from '@mui/material'; } from '@mui/material';
import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material'; import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material';
import axios from 'axios';
import { useParams, useLocation } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
import ItemDetails from './ItemDetails';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
import ItemDetails from './ItemDetails';
export default function Items({ token }) { export default function Items({ token }) {
const { id: boxId } = useParams(); const { id: boxId } = useParams();
const [items, setItems] = useState([]); const [items, setItems] = useState([]);
const [newItemName, setNewItemName] = useState(''); const [newItemName, setNewItemName] = useState('');
const [newItemDescription, setNewItemDescription] = useState(''); const [newItemDescription, setNewItemDescription] = useState('');
// const [newItemImagePath, setNewItemImagePath] = useState('/images/default.jpg');
const [editingItem, setEditingItem] = useState(null); const [editingItem, setEditingItem] = useState(null);
const location = useLocation(); const location = useLocation();
const boxName = location.state?.boxName || 'Unknown Box'; const boxName = location.state?.boxName || 'Unknown Box';
// const boxID = location.state?.boxId; // used in handleClose function
const [itemImages, setItemImages] = useState({}); const [itemImages, setItemImages] = useState({});
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
const [openAddItemDialog, setOpenAddItemDialog] = useState(false); // For Add Item dialog const [openAddItemDialog, setOpenAddItemDialog] = useState(false);
const { id } = useParams();
const boxID = id;
const url = boxId === undefined ? `${process.env.REACT_APP_API_URL}/api/v1/items` : `${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxId}/items`;
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const debugLog = (message) => { const { execute: fetchItems, loading: loadingItems, error: itemsError } = useApiCall();
if (process.env.DEBUG_API) { const { execute: createItem, loading: creatingItem, error: createError } = useApiCall();
console.log(message); const { execute: deleteItem, loading: deletingItem, error: deleteError } = useApiCall();
} const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
};
debugLog("Box ID: " + boxID);
// const handleSelectItem = (item) => { const url = boxId ?
// setSelectedItem(item); `${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxId}/items` :
// }; `${process.env.REACT_APP_API_URL}/api/v1/items`;
const handleAddItem = () => {
setOpenAddItemDialog(true);
};
const handleCloseAddItemDialog = () => { useEffect(() => {
setOpenAddItemDialog(false); const getItems = async () => {
setNewItemName(''); try {
setNewItemDescription(''); const response = await fetchItems(() =>
// setNewItemImagePath(''); api.items.getAll(token, boxId)
if (fileInputRef.current) { );
fileInputRef.current.value = '';
}
};
/**
* This function takes an image name and returns a unique image name.
* The purpose of this function is to prevent overwriting of images with the same name.
* If the image name is 'image.jpg', a random string is generated and appended to the image name.
* This is used to prevent overwriting of images with the same name.
* For example, if an image named 'image.jpg' is uploaded, the function will return 'image_8xgu6hcu.jpg'
* This ensures that the image will not overwrite any existing image with the same name.
* @param {string} imageName - The name of the image
* @return {string} - The unique image name
*/
const generateUniqueImageName = (imageName) => {
if (imageName.toLowerCase() === 'image.jpg') {
// Generate a random string
const randomString = Math.random().toString(36).substr(2, 9);
// Append the random string to the image name
return `image_${randomString}.jpg`;
}
// Return the original image name if it's not 'image.jpg'
return imageName;
};
const handleImageUpload = async (itemId, imageFile, newImageName) => {
const formData = new FormData();
//const imageFile = fileInputRef.current.files[0];
//const newImageName = generateUniqueImageName(imageFile.name);
formData.append('image', new File([imageFile], newImageName, {
type: imageFile.type,
}));
// Create a new file with the unique name
// eslint-disable-next-line
const newImageFile = new File([imageFile], newImageName, {
type: imageFile.type,
});
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}/upload`, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
});
// console.log('Image uploaded successfully!');
return response.data.imagePath; // Indicate successful upload
} catch (error) {
console.error('Image upload failed:', error);
return null; // Indicate upload failure
}
};
/**
* Handle saving a new item.
*
* This function first creates the item without the image, then if the item creation is successful,
* it uploads the image associated with the item.
*
* @return {Promise<void>}
*/
const handleSaveNewItem = async () => {
try {
const newItemResponse = await api.items.create(token, {
name: newItemName,
description: newItemDescription,
box_id: parseInt(boxId, 10)
});
if (newItemResponse.status === 200 && fileInputRef.current.files[0]) {
const newItemId = newItemResponse.data.id;
const imageFile = fileInputRef.current.files[0];
const newImageName = generateUniqueImageName(imageFile.name);
const formData = new FormData();
formData.append('image', new File([imageFile], newImageName, {
type: imageFile.type,
}));
await api.items.uploadImage(token, newItemId, formData);
}
handleCloseAddItemDialog();
fetchItems();
} catch (error) {
console.error('Error adding item:', error);
}
};
//const [selectedItem, setSelectedItem] = React.useState(null);
const handleCloseItemDetails = () => {
setEditingItem(null); // Close the ItemDetails modal
};
const handleImageError = (e) => {
if (e.target.src.startsWith('data:image/')) {
console.error("Default image failed to load. Check the file path.");
return;
}
const reader = new FileReader();
reader.onload = () => {
e.target.onerror = null;
e.target.src = reader.result;
};
fetch('/default.jpg')
.then(res => res.blob())
.then(blob => reader.readAsDataURL(blob))
.catch(error => console.error("Error loading default image:", error));
};
const getImageSrc = useCallback((itemId) => {
return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}/image`, {
headers: { Authorization: `Bearer ${token}` },
responseType: 'blob'
})
.then(response => {
if (response.status === 200) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(response.data);
});
} else {
throw new Error('Image fetch failed');
}
})
.catch(() => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = '/default.jpg';
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL());
};
img.onerror = reject;
});
});
}, [token]);
const fetchItems = useCallback(() => {
const fetchData = boxId ?
api.items.getByBox(token, boxId) :
api.items.getAll(token);
fetchData
.then(response => {
setItems(response.data); setItems(response.data);
// Fetch images for each item // Fetch images for each item
response.data.forEach(item => { response.data.forEach(item => {
api.items.getImage(token, item.ID) api.items.getImage(token, item.ID)
@ -240,61 +69,107 @@ export default function Items({ token }) {
})); }));
}; };
reader.readAsDataURL(response.data); reader.readAsDataURL(response.data);
})
.catch(() => {
setItemImages(prev => ({
...prev,
[item.ID]: '/default.jpg'
}));
}); });
}); });
}); } catch (err) {}
};
getItems();
}, [token, boxId]); }, [token, boxId]);
// lint says I don't need boxId here
useEffect(() => { const handleAddItem = () => {
fetchItems(); setOpenAddItemDialog(true);
}, [boxId, token, fetchItems]); };
// const handleAddItem = () => { const handleCloseAddItemDialog = () => {
// const formData = new FormData(); setOpenAddItemDialog(false);
// formData.append('name', newItemName); setNewItemName('');
// formData.append('description', newItemDescription); setNewItemDescription('');
// formData.append('box_id', parseInt(boxId, 10)); if (fileInputRef.current) {
// // Append image only if a new one is selected fileInputRef.current.value = '';
// if (fileInputRef.current.files[0]) { }
// formData.append('image', fileInputRef.current.files[0]); };
// }
// axios.post(`${process.env.REACT_APP_API_URL}/items`, formData, { const generateUniqueImageName = (imageName) => {
// headers: { if (imageName.toLowerCase() === 'image.jpg') {
// Authorization: `Bearer ${token}`, const randomString = Math.random().toString(36).substr(2, 9);
// 'Content-Type': 'multipart/form-data' // Important for file uploads return `image_${randomString}.jpg`;
// } }
// }).then(() => { return imageName;
// setNewItemName(''); };
// setNewItemDescription('');
// setNewItemImagePath('');
// // Clear the file input
// if (fileInputRef.current) {
// fileInputRef.current.value = '';
// }
// fetchItems();
// });
// };
const handleDeleteItem = (itemId) => { const handleSaveNewItem = async () => {
api.items.delete(token, itemId) try {
.then(() => { const newItemResponse = await createItem(() =>
fetchItems(); api.items.create(token, {
}); name: newItemName,
description: newItemDescription,
box_id: parseInt(boxId, 10)
})
);
if (newItemResponse.status === 200 && fileInputRef.current?.files?.[0]) {
const imageFile = fileInputRef.current.files[0];
const newImageName = generateUniqueImageName(imageFile.name);
const formData = new FormData();
formData.append('image', new File([imageFile], newImageName, {
type: imageFile.type,
}));
await uploadImage(() =>
api.items.uploadImage(token, newItemResponse.data.id, formData)
);
}
handleCloseAddItemDialog();
// Refresh items list
const response = await fetchItems(() =>
api.items.getAll(token, boxId)
);
setItems(response.data);
} catch (err) {}
};
const handleDeleteItem = async (itemId) => {
try {
await deleteItem(() =>
api.items.delete(token, itemId)
);
setItems(items.filter(item => item.ID !== itemId));
} catch (err) {}
}; };
const handleEditItem = (item) => { const handleEditItem = (item) => {
setEditingItem(item); setEditingItem(item);
}; };
const handleSaveEdit = () => { const handleSaveEdit = async () => {
setEditingItem(null); setEditingItem(null);
fetchItems(); const response = await fetchItems(() =>
api.items.getAll(token, boxId)
);
setItems(response.data);
}; };
const filteredItems = items.filter(item =>
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(searchQuery.toLowerCase())
);
return ( return (
<Container> <Container>
{(itemsError || createError || deleteError || uploadError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{itemsError?.message || createError?.message || deleteError?.message || uploadError?.message}
</Alert>
)}
<TextField <TextField
label="Search" label="Search"
variant="outlined" variant="outlined"
@ -303,20 +178,18 @@ export default function Items({ token }) {
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
/> />
<h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : `${boxName} (${items.length} items)`}</h2>
<input
type="file"
accept="image/*"
ref={fileInputRef}
style={{ display: 'none' }}
id="newItemImageUpload" // Unique ID
/>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}variant="contained" color="primary" onClick={handleAddItem}> <h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : `${boxName} (${items.length} items)`}</h2>
Add Item
<Button
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={handleAddItem}
disabled={creatingItem}
>
{creatingItem ? <CircularProgress size={24} /> : 'Add Item'}
</Button> </Button>
{/* Dialog for adding new item */}
<Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}> <Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}>
<DialogTitle>Add New Item</DialogTitle> <DialogTitle>Add New Item</DialogTitle>
<DialogContent> <DialogContent>
@ -340,75 +213,80 @@ export default function Items({ token }) {
type="file" type="file"
accept="image/*" accept="image/*"
ref={fileInputRef} ref={fileInputRef}
// capture="environment" // Capture the image from the user's camera style={{ display: 'block', margin: '10px 0' }}
style={{ display: 'block', margin: '10px 0' }} // Style as needed
id="newItemImageUpload"
/> />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={handleCloseAddItemDialog}>Cancel</Button> <Button onClick={handleCloseAddItemDialog}>Cancel</Button>
<Button onClick={handleSaveNewItem} color="primary"> <Button
Save onClick={handleSaveNewItem}
color="primary"
disabled={creatingItem || !newItemName.trim()}
>
{creatingItem ? <CircularProgress size={24} /> : 'Save'}
</Button> </Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
{editingItem ? (
{editingItem && (
<ItemDetails <ItemDetails
item={editingItem} item={editingItem}
token={token} token={token}
onSave={handleSaveEdit} onSave={handleSaveEdit}
onClose={handleCloseItemDetails} onClose={() => setEditingItem(null)}
boxId={boxId} boxId={boxId}
/> />
)}
{loadingItems ? (
<CircularProgress />
) : ( ) : (
<TableContainer> <TableContainer>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell style={{ width: '40px' }}>Image</TableCell> <TableCell style={{ width: '40px' }}>Image</TableCell>
<TableCell style={{ width: '100px' }}>Name</TableCell> <TableCell style={{ width: '100px' }}>Name</TableCell>
<TableCell>Description</TableCell> <TableCell>Description</TableCell>
<TableCell>Actions</TableCell> <TableCell>Actions</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{items {filteredItems.map((item) => (
.filter(item =>
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(searchQuery.toLowerCase())
)
.map((item) => (
<TableRow key={item.ID}> <TableRow key={item.ID}>
<TableCell> <TableCell>
<Avatar src={itemImages[item.ID] || '/images/default.jpg'} /> <Avatar src={itemImages[item.ID] || '/images/default.jpg'} />
</TableCell> </TableCell>
<TableCell>{item.name}</TableCell> <TableCell>{item.name}</TableCell>
<TableCell>{item.description}</TableCell> <TableCell>{item.description}</TableCell>
<Box display="flex" justifyContent="space-between" width="100%"> <TableCell>
<Tooltip title="Edit Item"> <Box display="flex" justifyContent="space-between" width="100%">
<IconButton <Tooltip title="Edit Item">
onClick={() => handleEditItem(item)} <IconButton
size="large" onClick={() => handleEditItem(item)}
sx={{ mr: 1 }} size="large"
> sx={{ mr: 1 }}
<EditIcon /> >
</IconButton> <EditIcon />
</Tooltip> </IconButton>
<Tooltip title="Delete Item"> </Tooltip>
<IconButton <Tooltip title="Delete Item">
onClick={() => handleDeleteItem(item.ID)} <IconButton
size="large" onClick={() => handleDeleteItem(item.ID)}
color="error" size="large"
> color="error"
<DeleteIcon /> disabled={deletingItem}
</IconButton> >
</Tooltip> {deletingItem ? <CircularProgress size={20} /> : <DeleteIcon />}
</Box> </IconButton>
</Tooltip>
</Box>
</TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
</Table> </Table>
</TableContainer> </TableContainer>
)} )}
</Container> </Container>
); );

View File

@ -1,27 +1,26 @@
// src/components/Login.js // src/components/Login.js
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Button, TextField, Container, Typography, Alert } from '@mui/material'; import { Button, TextField, Container, Typography, Alert, CircularProgress } from '@mui/material';
import { useNavigate } from 'react-router-dom'; // Import useNavigate import { useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api'; import { api } from '../services/api';
import { useApiCall } from './hooks/useApiCall';
export default function Login({ setToken }) { export default function Login({ setToken }) {
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
const { execute, loading, error } = useApiCall();
const handleLogin = async (e) => { const handleLogin = async (e) => {
e.preventDefault(); e.preventDefault();
setLoginError(false);
try { try {
const response = await api.login({ username, password }); const response = await execute(() => api.login({ username, password }));
setToken(response.data.token); setToken(response.data.token);
navigate('/boxes'); navigate('/boxes');
} catch (error) { } catch (err) {
console.error('Login failed', error); // Error handling is now managed by useApiCall
setLoginError(true); console.error('Login attempt failed');
} }
}; };
@ -29,9 +28,10 @@ export default function Login({ setToken }) {
<Container maxWidth="xs"> <Container maxWidth="xs">
<Typography variant="h4" gutterBottom>Login</Typography> <Typography variant="h4" gutterBottom>Login</Typography>
{/* Display error message if loginError is true */} {error && (
{loginError && ( <Alert severity="error">
<Alert severity="error">Login Failed</Alert> {error.status === 401 ? 'Invalid username or password' : error.message}
</Alert>
)} )}
<form onSubmit={handleLogin}> <form onSubmit={handleLogin}>
@ -52,8 +52,15 @@ export default function Login({ setToken }) {
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" type="submit" fullWidth> <Button
Login sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
color="primary"
type="submit"
fullWidth
disabled={loading}
>
{loading ? <CircularProgress size={24} /> : 'Login'}
</Button> </Button>
</form> </form>
</Container> </Container>

View File

@ -0,0 +1,43 @@
import { useState } from 'react';
/**
* useApiCall hook.
*
* This hook helps to wrap API calls in a way that makes it easier to manage
* loading state and errors.
*
* @returns {Object} An object with `execute`, `loading`, and `error`
* properties. `execute` is a function that wraps the API call and sets the
* `loading` and `error` states accordingly. `loading` is a boolean that is
* `true` while the API call is in progress and `false` otherwise. `error` is
* `null` if the API call was successful and an error object if the API call
* failed.
*
* @example
* const { execute, loading, error } = useApiCall();
*
* const fetchData = async () => {
* const response = await execute(api.items.getAll());
* // Do something with the response
* };
*/
export const useApiCall = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const execute = async (apiCall) => {
setLoading(true);
setError(null);
try {
const result = await apiCall();
return result;
} catch (err) {
setError(err);
throw err;
} finally {
setLoading(false);
}
};
return { execute, loading, error };
};

View File

@ -0,0 +1,36 @@
// src/utils/errorHandler.js
import axios from 'axios';
export class ApiError extends Error {
constructor(message, status, details = {}) {
super(message);
this.status = status;
this.details = details;
}
}
// Enhanced API client with error handling
export const createApiClient = () => {
const client = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
client.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
return Promise.reject(new ApiError('Session expired', 401));
}
return Promise.reject(new ApiError(
error.response?.data?.message || 'An error occurred',
error.response?.status,
error.response?.data
));
}
);
return client;
};