error-handling #1
|
@ -1,9 +1,10 @@
|
||||||
// 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,
|
||||||
|
@ -18,10 +19,9 @@ import {
|
||||||
Container,
|
Container,
|
||||||
Box,
|
Box,
|
||||||
TextField,
|
TextField,
|
||||||
Tab
|
CircularProgress
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
|
|
||||||
|
|
||||||
export default function Admin() {
|
export default function Admin() {
|
||||||
const [users, setUsers] = useState([]);
|
const [users, setUsers] = useState([]);
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
|
@ -30,85 +30,92 @@ import {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const fileInputRef = useRef(null);
|
const fileInputRef = useRef(null);
|
||||||
|
|
||||||
useEffect(() => {
|
const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall();
|
||||||
fetchUsers();
|
const { execute: createUser, loading: creatingUser, error: createError } = useApiCall();
|
||||||
}, []);
|
const { execute: deleteUser, loading: deletingUser, error: deleteError } = useApiCall();
|
||||||
|
const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall();
|
||||||
|
const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall();
|
||||||
|
|
||||||
const fetchUsers = async () => {
|
useEffect(() => {
|
||||||
|
const getUsers = 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]);
|
setUsers([...users, response.data]);
|
||||||
setUsername('');
|
setUsername('');
|
||||||
setPassword('');
|
setPassword('');
|
||||||
setEmail('');
|
setEmail('');
|
||||||
} catch (error) {
|
} catch (err) {}
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteUser = async (id) => {
|
const handleDeleteUser = async (id) => {
|
||||||
try {
|
try {
|
||||||
await api.admin.deleteUser(localStorage.getItem('token'), id);
|
await deleteUser(() =>
|
||||||
|
api.admin.deleteUser(localStorage.getItem('token'), id)
|
||||||
|
);
|
||||||
setUsers(users.filter(user => user.id !== id));
|
setUsers(users.filter(user => user.id !== id));
|
||||||
fetchUsers();
|
} catch (err) {}
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBackupDatabase = async () => {
|
const handleBackupDatabase = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await api.admin.backupDb(localStorage.getItem('token'));
|
const response = await backupDB(() =>
|
||||||
|
api.admin.backupDB(localStorage.getItem('token'))
|
||||||
|
);
|
||||||
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
|
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = 'database.db';
|
a.download = 'database.db';
|
||||||
a.click();
|
a.click();
|
||||||
} catch (error) {
|
} catch (err) {}
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRestoreDatabase = async (e) => {
|
const handleRestoreDatabase = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!fileInputRef.current?.files?.[0]) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const file = fileInputRef.current.files[0];
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('database', file);
|
formData.append('database', fileInputRef.current.files[0]);
|
||||||
|
|
||||||
const response = await api.admin.restoreDb(localStorage.getItem('token'), formData);
|
await restoreDB(() =>
|
||||||
|
api.admin.restoreDB(localStorage.getItem('token'), formData)
|
||||||
if (response.status === 200) {
|
);
|
||||||
alert('Database restored successfully');
|
alert('Database restored successfully');
|
||||||
navigate('/admin');
|
navigate('/admin');
|
||||||
}
|
} catch (err) {}
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
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,12 +143,21 @@ 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>
|
||||||
|
|
||||||
|
{loadingUsers ? (
|
||||||
|
<CircularProgress />
|
||||||
|
) : (
|
||||||
<TableContainer component={Paper}>
|
<TableContainer component={Paper}>
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead>
|
||||||
|
@ -153,16 +171,17 @@ import {
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{users.map(user => (
|
{users.map(user => (
|
||||||
<TableRow key={user.ID}>
|
<TableRow key={user.ID}>
|
||||||
<TableCell style={{ width: '30px' }}>{user.ID}</TableCell>
|
<TableCell>{user.ID}</TableCell>
|
||||||
<TableCell style={{ width: '100px'}}>{user.username}</TableCell>
|
<TableCell>{user.username}</TableCell>
|
||||||
<TableCell style={{ width: '300px'}}>{user.email}</TableCell>
|
<TableCell>{user.email}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Button
|
<Button
|
||||||
variant="contained"
|
variant="contained"
|
||||||
color="error"
|
color="error"
|
||||||
onClick={() => handleDeleteUser(user.ID)}
|
onClick={() => handleDeleteUser(user.ID)}
|
||||||
|
disabled={deletingUser}
|
||||||
>
|
>
|
||||||
Delete User
|
{deletingUser ? <CircularProgress size={24} /> : 'Delete User'}
|
||||||
</Button>
|
</Button>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
|
@ -170,24 +189,25 @@ import {
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</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
|
||||||
|
|
|
@ -1,50 +1,75 @@
|
||||||
// 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(() => {
|
||||||
|
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);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loadingBoxes ? (
|
||||||
|
<CircularProgress />
|
||||||
|
) : (
|
||||||
<TableContainer>
|
<TableContainer>
|
||||||
<Table size="small">
|
<Table size="small">
|
||||||
<TableHead>
|
<TableHead>
|
||||||
|
@ -62,8 +87,12 @@ export default function Boxes({ token }) {
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Button onClick={() => handleDeleteBox(box.ID)} startIcon={<DeleteIcon />}>
|
<Button
|
||||||
Delete
|
onClick={() => handleDeleteBox(box.ID)}
|
||||||
|
startIcon={<DeleteIcon />}
|
||||||
|
disabled={deletingBox}
|
||||||
|
>
|
||||||
|
{deletingBox ? <CircularProgress size={20} /> : 'Delete'}
|
||||||
</Button>
|
</Button>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
|
@ -71,15 +100,23 @@ export default function Boxes({ token }) {
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</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>
|
||||||
);
|
);
|
||||||
|
|
|
@ -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>
|
||||||
|
|
||||||
|
{(error || boxesError || saveError || uploadError) && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{error?.message || boxesError?.message || saveError?.message || uploadError?.message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<CircularProgress />
|
||||||
|
) : (
|
||||||
<Tooltip title="Click to enlarge">
|
<Tooltip title="Click to enlarge">
|
||||||
<Avatar
|
<Avatar
|
||||||
src={imageSrc}
|
src={imageSrc}
|
||||||
alt={name}
|
alt={name}
|
||||||
onError={handleImageError}
|
|
||||||
sx={{ width: 200, height: 200, marginBottom: '16px' }}
|
sx={{ width: 200, height: 200, marginBottom: '16px' }}
|
||||||
onClick={handleAvatarClick}
|
onClick={() => setImageOverlayVisible(true)}
|
||||||
/>
|
/>
|
||||||
</Tooltip>
|
</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,24 +134,17 @@ 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
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
ref={fileInputRef}
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
id="editItemImageUpload"
|
|
||||||
/>
|
|
||||||
<select value={selectedBoxId} onChange={handleBoxChange}>
|
|
||||||
<option value="">No box</option>
|
<option value="">No box</option>
|
||||||
{boxes.map((box) => (
|
{boxes.map((box) => (
|
||||||
<option key={box.ID} value={box.ID}>
|
<option key={box.ID} value={box.ID}>
|
||||||
|
@ -176,25 +152,44 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
)}
|
||||||
|
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" component="label" htmlFor="editItemImageUpload">
|
|
||||||
Upload Image
|
<Button
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
variant="contained"
|
||||||
|
component="label"
|
||||||
|
disabled={uploadingImage || savingItem}
|
||||||
|
>
|
||||||
|
{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>
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -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 = () => {
|
|
||||||
setOpenAddItemDialog(false);
|
|
||||||
setNewItemName('');
|
|
||||||
setNewItemDescription('');
|
|
||||||
// setNewItemImagePath('');
|
|
||||||
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,
|
|
||||||
});
|
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const getItems = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}/upload`, formData, {
|
const response = await fetchItems(() =>
|
||||||
headers: {
|
api.items.getAll(token, boxId)
|
||||||
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 () => {
|
||||||
|
try {
|
||||||
|
const newItemResponse = await createItem(() =>
|
||||||
|
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)
|
api.items.delete(token, itemId)
|
||||||
.then(() => {
|
);
|
||||||
fetchItems();
|
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,26 +213,33 @@ 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>
|
||||||
|
@ -372,18 +252,14 @@ export default function Items({ token }) {
|
||||||
</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>
|
||||||
|
<TableCell>
|
||||||
<Box display="flex" justifyContent="space-between" width="100%">
|
<Box display="flex" justifyContent="space-between" width="100%">
|
||||||
<Tooltip title="Edit Item">
|
<Tooltip title="Edit Item">
|
||||||
<IconButton
|
<IconButton
|
||||||
|
@ -399,11 +275,13 @@ export default function Items({ token }) {
|
||||||
onClick={() => handleDeleteItem(item.ID)}
|
onClick={() => handleDeleteItem(item.ID)}
|
||||||
size="large"
|
size="large"
|
||||||
color="error"
|
color="error"
|
||||||
|
disabled={deletingItem}
|
||||||
>
|
>
|
||||||
<DeleteIcon />
|
{deletingItem ? <CircularProgress size={20} /> : <DeleteIcon />}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Box>
|
</Box>
|
||||||
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
|
|
|
@ -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>
|
||||||
|
|
|
@ -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 };
|
||||||
|
};
|
|
@ -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;
|
||||||
|
};
|
Loading…
Reference in New Issue