Compare commits

..

2 Commits

Author SHA1 Message Date
Steve White e0f7af5e88 GUI improvements 2024-11-01 23:47:37 -05:00
Steve White 74502b1077 Added tagging to the UI and fixed the back end. 2024-10-31 11:57:33 -05:00
11 changed files with 949 additions and 499 deletions

20
package-lock.json generated
View File

@ -16,7 +16,7 @@
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"axios": "^1.7.7", "axios": "^1.7.7",
"jwt-decode": "^4.0.0", "lucide-react": "^0.454.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
@ -13780,15 +13780,6 @@
"node": ">=4.0" "node": ">=4.0"
} }
}, },
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": { "node_modules/keyv": {
"version": "4.5.4", "version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@ -13991,6 +13982,15 @@
"yallist": "^3.0.2" "yallist": "^3.0.2"
} }
}, },
"node_modules/lucide-react": {
"version": "0.454.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.454.0.tgz",
"integrity": "sha512-hw7zMDwykCLnEzgncEEjHeA6+45aeEzRYuKHuyRSOPkhko+J3ySGjGIzu+mmMfDFG1vazHepMaYFYHbTFAZAAQ==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
}
},
"node_modules/lz-string": { "node_modules/lz-string": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",

View File

@ -11,7 +11,7 @@
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"axios": "^1.7.7", "axios": "^1.7.7",
"jwt-decode": "^4.0.0", "lucide-react": "^0.454.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",

View File

@ -1,55 +1,22 @@
// src/App.js // src/App.js
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate, useNavigate } from 'react-router-dom'; import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { jwtDecode } from 'jwt-decode';
import Login from './components/Login'; import Login from './components/Login';
import Boxes from './components/Boxes'; import Boxes from './components/Boxes';
import Items from './components/Items'; import Items from './components/Items';
import Navbar from './components/Navbar'; import Navbar from './components/Navbar'; // Correct import here
import Admin from './components/Admin'; import Admin from './components/Admin'; // Correct import here
import { createContext } from 'react'; import { createContext } from 'react';
import ErrorBoundary from './components/ErrorBoundary';
import './styles.css' import './styles.css'
import { EnhancedThemeProvider } from './components/themeProvider';
export const AppContext = createContext(); export const AppContext = createContext();
export const PRIMARY_COLOR = '#333'; export const PRIMARY_COLOR = '#333';
export const SECONDARY_COLOR = '#ffffff'; export const SECONDARY_COLOR = '#ffffff';
export const BACKGROUND_COLOR = '#dddddd'; export const BACKGROUND_COLOR = '#dddddd';
// New component for token expiration check
function TokenExpirationCheck({ setToken }) {
const navigate = useNavigate();
useEffect(() => {
const checkTokenExpiration = () => {
const token = localStorage.getItem('token');
if (!token) return;
try {
const decodedToken = jwtDecode(token);
if (Date.now() >= decodedToken.exp * 1000) {
setToken(null);
localStorage.removeItem('token');
navigate('/api/v1/login');
}
} catch (error) {
localStorage.removeItem('token');
navigate('/api/v1/login');
}
};
window.addEventListener('focus', checkTokenExpiration);
const interval = setInterval(checkTokenExpiration, 60000);
return () => {
window.removeEventListener('focus', checkTokenExpiration);
clearInterval(interval);
};
}, [navigate, setToken]);
return null;
}
function App() { function App() {
const [token, setToken] = useState(localStorage.getItem('token')); const [token, setToken] = useState(localStorage.getItem('token'));
@ -60,18 +27,21 @@ function App() {
}, [token]); }, [token]);
return ( return (
<AppContext.Provider value={{ token, setToken }}> <EnhancedThemeProvider>
<Router> <AppContext.Provider value={{ token, setToken }}>
<TokenExpirationCheck setToken={setToken} /> <ErrorBoundary>
<Navbar /> <Router>
<AppRoutes token={token} setToken={setToken} /> <Navbar />
</Router> <AppRoutes token={token} setToken={setToken} />
</AppContext.Provider> </Router>
</ErrorBoundary>
</AppContext.Provider>
</EnhancedThemeProvider>
); );
} }
function AppRoutes({ token, setToken }) { function AppRoutes({ token, setToken }) {
const { id } = useParams(); const { id } = useParams(); // Move useParams here
return ( return (
<> <>
@ -98,5 +68,4 @@ function AppRoutes({ token, setToken }) {
</> </>
); );
} }
export default App; export default App;

View File

@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios'; // 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 './Admin.css';
@ -19,33 +19,41 @@ import {
Container, Container,
Box, Box,
TextField, TextField,
CircularProgress CircularProgress,
Tab,
Tabs
} from '@mui/material'; } from '@mui/material';
export default function Admin() { export default function Admin() {
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
const [tags, setTags] = useState([]);
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [activeTab, setActiveTab] = useState(0);
const navigate = useNavigate(); const navigate = useNavigate();
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall(); const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall();
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
const { execute: createUser, loading: creatingUser, error: createError } = useApiCall(); const { execute: createUser, loading: creatingUser, error: createError } = useApiCall();
const { execute: deleteUser, loading: deletingUser, error: deleteError } = useApiCall(); const { execute: deleteUser, loading: deletingUser, error: deleteError } = useApiCall();
const { execute: deleteTag, loading: deletingTag, error: deleteTagError } = useApiCall();
const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall(); const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall();
const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall(); const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall();
useEffect(() => { useEffect(() => {
const getUsers = async () => { const getInitialData = async () => {
try { try {
const response = await fetchUsers(() => const [usersResponse, tagsResponse] = await Promise.all([
api.admin.getUsers(localStorage.getItem('token')) fetchUsers(() => api.admin.getUsers(localStorage.getItem('token'))),
); fetchTags(() => api.tags.getAll(localStorage.getItem('token')))
setUsers(response.data); ]);
setUsers(usersResponse.data);
setTags(tagsResponse.data);
} catch (err) {} } catch (err) {}
}; };
getUsers(); getInitialData();
}, []); }, []);
const handleCreateUser = async (e) => { const handleCreateUser = async (e) => {
@ -73,6 +81,19 @@ export default function Admin() {
} catch (err) {} } catch (err) {}
}; };
const handleDeleteTag = async (tagId) => {
if (!window.confirm('Are you sure you want to delete this tag? This will remove it from all items.')) {
return;
}
try {
await deleteTag(() =>
api.tags.delete(localStorage.getItem('token'), tagId)
);
setTags(tags.filter(tag => tag.ID !== tagId));
} catch (err) {}
};
const handleBackupDatabase = async () => { const handleBackupDatabase = async () => {
try { try {
const response = await backupDB(() => const response = await backupDB(() =>
@ -109,113 +130,180 @@ export default function Admin() {
Admin Dashboard Admin Dashboard
</Typography> </Typography>
{(usersError || createError || deleteError || backupError || restoreError) && ( {(usersError || createError || deleteError || backupError || restoreError || tagsError || deleteTagError) && (
<Alert severity="error" sx={{ mb: 2 }}> <Alert severity="error" sx={{ mb: 2 }}>
{usersError?.message || createError?.message || deleteError?.message || {usersError?.message || createError?.message || deleteError?.message ||
backupError?.message || restoreError?.message} backupError?.message || restoreError?.message || tagsError?.message || deleteTagError?.message}
</Alert> </Alert>
)} )}
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}> <Tabs value={activeTab} onChange={(e, newValue) => setActiveTab(newValue)} sx={{ mb: 3 }}>
<Typography variant="h6" gutterBottom> <Tab label="Users" />
Add New User <Tab label="Tags" />
</Typography> <Tab label="Database" />
<TextField </Tabs>
label="Username"
variant="outlined"
value={username}
onChange={(e) => setUsername(e.target.value)}
sx={{ mr: 2 }}
disabled={creatingUser}
/>
<TextField
label="Password"
type="password"
variant="outlined"
value={password}
onChange={(e) => setPassword(e.target.value)}
sx={{ mr: 2 }}
disabled={creatingUser}
/>
<TextField
label="Email"
variant="outlined"
value={email}
onChange={(e) => setEmail(e.target.value)}
sx={{ mr: 2 }}
disabled={creatingUser}
/>
<Button
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>
</Box>
{loadingUsers ? ( {activeTab === 0 && (
<CircularProgress /> <>
) : ( <Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
<TableContainer component={Paper}> <Typography variant="h6" gutterBottom>
<Table> Add New User
<TableHead> </Typography>
<TableRow> <TextField
<TableCell>ID</TableCell> label="Username"
<TableCell>Username</TableCell> variant="outlined"
<TableCell>Email</TableCell> value={username}
<TableCell>Actions</TableCell> onChange={(e) => setUsername(e.target.value)}
</TableRow> sx={{ mr: 2 }}
</TableHead> disabled={creatingUser}
<TableBody> />
{users.map(user => ( <TextField
<TableRow key={user.ID}> label="Password"
<TableCell>{user.ID}</TableCell> type="password"
<TableCell>{user.username}</TableCell> variant="outlined"
<TableCell>{user.email}</TableCell> value={password}
<TableCell> onChange={(e) => setPassword(e.target.value)}
<Button sx={{ mr: 2 }}
variant="contained" disabled={creatingUser}
color="error" />
onClick={() => handleDeleteUser(user.ID)} <TextField
disabled={deletingUser} label="Email"
> variant="outlined"
{deletingUser ? <CircularProgress size={24} /> : 'Delete User'} value={email}
</Button> onChange={(e) => setEmail(e.target.value)}
</TableCell> sx={{ mr: 2 }}
</TableRow> disabled={creatingUser}
))} />
</TableBody> <Button
</Table> type="submit"
</TableContainer> sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
disabled={creatingUser}
>
{creatingUser ? <CircularProgress size={24} /> : 'Add User'}
</Button>
</Box>
{loadingUsers ? (
<CircularProgress />
) : (
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Username</TableCell>
<TableCell>Email</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map(user => (
<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 }}> {activeTab === 1 && (
<Button <>
variant="contained" <Typography variant="h6" gutterBottom>
onClick={handleBackupDatabase} Manage Tags
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} </Typography>
disabled={backingUp} {loadingTags ? (
> <CircularProgress />
{backingUp ? <CircularProgress size={24} /> : 'Backup Database'} ) : (
</Button> <TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Color</TableCell>
<TableCell>Name</TableCell>
<TableCell>Description</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{tags.map(tag => (
<TableRow key={tag.ID}>
<TableCell>
<Box
sx={{
width: 24,
height: 24,
backgroundColor: tag.color,
borderRadius: '50%'
}}
/>
</TableCell>
<TableCell>{tag.name}</TableCell>
<TableCell>{tag.description}</TableCell>
<TableCell>
<Button
variant="contained"
color="error"
onClick={() => handleDeleteTag(tag.ID)}
disabled={deletingTag}
>
{deletingTag ? <CircularProgress size={24} /> : 'Delete Tag'}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</>
)}
<Button {activeTab === 2 && (
variant="contained" <Box sx={{ mt: 4 }}>
component="label" <Typography variant="h6" gutterBottom>
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} Database Management
disabled={restoring} </Typography>
> <Button
{restoring ? <CircularProgress size={24} /> : 'Restore Database'} variant="contained"
<input onClick={handleBackupDatabase}
type="file" sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
hidden disabled={backingUp}
ref={fileInputRef} >
onChange={handleRestoreDatabase} {backingUp ? <CircularProgress size={24} /> : 'Backup Database'}
/> </Button>
</Button>
</Box> <Button
variant="contained"
component="label"
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
disabled={restoring}
>
{restoring ? <CircularProgress size={24} /> : 'Restore Database'}
<input
type="file"
hidden
ref={fileInputRef}
onChange={handleRestoreDatabase}
/>
</Button>
</Box>
)}
</Container> </Container>
); );
} }

View File

@ -10,9 +10,11 @@ import {
TableHead, TableHead,
TableRow, TableRow,
Alert, Alert,
CircularProgress CircularProgress,
Avatar,
Box
} from '@mui/material'; } from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material'; import { Delete as DeleteIcon, Inventory as InventoryIcon } from '@mui/icons-material';
import { Link as RouterLink } 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 { useApiCall } from './hooks/useApiCall';
@ -36,7 +38,7 @@ export default function Boxes({ token }) {
} catch (err) {} } catch (err) {}
}; };
getBoxes(); getBoxes();
}, [token]); // Remove fetchBoxes from dependencies }, [token]);
const handleCreateBox = async () => { const handleCreateBox = async () => {
if (!newBoxName.trim()) return; if (!newBoxName.trim()) return;
@ -74,23 +76,50 @@ export default function Boxes({ token }) {
<Table size="small"> <Table size="small">
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell width="48px"></TableCell>
<TableCell>Box Name</TableCell> <TableCell>Box Name</TableCell>
<TableCell>Actions</TableCell> <TableCell align="right">Actions</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{boxes.map((box) => ( {boxes.map((box) => (
<TableRow key={box.ID}> <TableRow key={box.ID}>
<TableCell> <TableCell>
<RouterLink to={`/api/v1/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}> <Avatar
{box.name} sx={{
</RouterLink> bgcolor: PRIMARY_COLOR,
width: 32,
height: 32
}}
>
<InventoryIcon sx={{ color: SECONDARY_COLOR, fontSize: 20 }} />
</Avatar>
</TableCell> </TableCell>
<TableCell> <TableCell>
<Box
component={RouterLink}
to={`/api/v1/boxes/${box.ID}/items`}
state={{ boxName: box.name, boxID: box.ID }}
sx={{
textDecoration: 'none',
color: 'inherit',
display: 'flex',
alignItems: 'center',
'&:hover': {
textDecoration: 'underline'
}
}}
>
{box.name}
</Box>
</TableCell>
<TableCell align="right">
<Button <Button
onClick={() => handleDeleteBox(box.ID)} onClick={() => handleDeleteBox(box.ID)}
startIcon={<DeleteIcon />} startIcon={<DeleteIcon />}
disabled={deletingBox} disabled={deletingBox}
color="error"
size="small"
> >
{deletingBox ? <CircularProgress size={20} /> : 'Delete'} {deletingBox ? <CircularProgress size={20} /> : 'Delete'}
</Button> </Button>
@ -102,22 +131,31 @@ export default function Boxes({ token }) {
</TableContainer> </TableContainer>
)} )}
<TextField <Box sx={{ mt: 2 }}>
label="New Box" <TextField
variant="outlined" label="New Box"
fullWidth variant="outlined"
value={newBoxName} fullWidth
onChange={(e) => setNewBoxName(e.target.value)} value={newBoxName}
disabled={creatingBox} onChange={(e) => setNewBoxName(e.target.value)}
/> disabled={creatingBox}
<Button sx={{ mb: 1 }}
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} />
variant="contained" <Button
onClick={handleCreateBox} sx={{
disabled={creatingBox || !newBoxName.trim()} backgroundColor: PRIMARY_COLOR,
> borderBottom: '1px solid',
{creatingBox ? <CircularProgress size={24} /> : 'Add Box'} borderColor: '#444',
</Button> color: SECONDARY_COLOR
}}
variant="contained"
onClick={handleCreateBox}
disabled={creatingBox || !newBoxName.trim()}
fullWidth
>
{creatingBox ? <CircularProgress size={24} /> : 'Add Box'}
</Button>
</Box>
</Container> </Container>
); );
} }

View File

@ -1,55 +1,76 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { TextField, Button, Container, Avatar, Tooltip, Alert, CircularProgress } from '@mui/material'; import {
TextField,
Button,
Container,
Avatar,
Tooltip,
Alert,
CircularProgress,
Box,
Typography
} from '@mui/material';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall'; import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
import TagManager from './tagManager';
export default function ItemDetails({ item, token, onSave, onClose }) { export default function ItemDetails({ item: initialItem, token, onSave, onClose }) {
const [name, setName] = useState(item.name); const [item, setItem] = useState(initialItem);
const [description, setDescription] = useState(item.description); const [name, setName] = useState(initialItem.name);
const [imagePath, setImagePath] = useState(item.image_path || ''); const [description, setDescription] = useState(initialItem.description);
const [imagePath, setImagePath] = useState(initialItem.image_path || '');
const [imageSrc, setImageSrc] = useState('/images/default.jpg'); const [imageSrc, setImageSrc] = useState('/images/default.jpg');
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
const [imageOverlayVisible, setImageOverlayVisible] = useState(false); const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [selectedBoxId, setSelectedBoxId] = useState(item.box_id); const [selectedBoxId, setSelectedBoxId] = useState(initialItem.box_id);
const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall(); const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
const { execute: fetchItem, loading: loadingItem } = useApiCall();
const { execute: updateItem, loading: savingItem, error: saveError } = useApiCall(); const { execute: updateItem, loading: savingItem, error: saveError } = useApiCall();
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall(); const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
// Single effect to load initial data
useEffect(() => { useEffect(() => {
const getBoxes = async () => { const loadInitialData = async () => {
try { try {
const response = await fetchBoxes(() => api.boxes.getAll(token)); // Fetch item and boxes in parallel
setBoxes(response.data); const [itemResponse, boxesResponse] = await Promise.all([
} catch (err) {} fetchItem(() => api.items.getOne(token, initialItem.ID)),
}; fetchBoxes(() => api.boxes.getAll(token))
getBoxes(); ]);
}, [token]);
useEffect(() => { const updatedItem = itemResponse.data;
const loadImage = async () => { setItem(updatedItem);
setLoading(true); setName(updatedItem.name);
setError(null); setDescription(updatedItem.description);
try { setImagePath(updatedItem.image_path || '');
const response = await api.items.getImage(token, item.ID); setBoxes(boxesResponse.data);
const reader = new FileReader();
reader.onload = () => { // Load image
setImageSrc(reader.result); try {
const imageResponse = await api.items.getImage(token, initialItem.ID);
const reader = new FileReader();
reader.onload = () => {
setImageSrc(reader.result);
setLoading(false);
};
reader.readAsDataURL(imageResponse.data);
} catch (err) {
setImageSrc('/default.jpg');
setLoading(false); setLoading(false);
}; }
reader.readAsDataURL(response.data);
} catch (err) { } catch (err) {
setImageSrc('/default.jpg');
setError(err); setError(err);
setLoading(false); setLoading(false);
} }
}; };
loadImage();
}, [item.ID, token]); loadInitialData();
}, []); // Empty dependency array - only run once on mount
const handleImageUpload = async () => { const handleImageUpload = async () => {
if (!fileInputRef.current?.files?.[0]) return null; if (!fileInputRef.current?.files?.[0]) return null;
@ -86,9 +107,13 @@ export default function ItemDetails({ item, token, onSave, onClose }) {
setSelectedBoxId(event.target.value); setSelectedBoxId(event.target.value);
}; };
const handleTagsChange = (newTags) => {
setItem(prev => ({...prev, tags: newTags}));
};
return ( return (
<Container> <Container>
<h3>Edit Item: {item.name}</h3> <h3>Edit Item: {name}</h3>
{(error || boxesError || saveError || uploadError) && ( {(error || boxesError || saveError || uploadError) && (
<Alert severity="error" sx={{ mb: 2 }}> <Alert severity="error" sx={{ mb: 2 }}>
@ -99,97 +124,107 @@ export default function ItemDetails({ item, token, onSave, onClose }) {
{loading ? ( {loading ? (
<CircularProgress /> <CircularProgress />
) : ( ) : (
<Tooltip title="Click to enlarge"> /* Rest of your JSX remains the same */
<Avatar // ... existing JSX code ...
src={imageSrc} <Box>
alt={name} {/* Image section */}
sx={{ width: 200, height: 200, marginBottom: '16px' }} <Tooltip title="Click to enlarge">
onClick={() => setImageOverlayVisible(true)} <Avatar
src={imageSrc}
alt={name}
sx={{ width: 200, height: 200, marginBottom: '16px' }}
onClick={() => setImageOverlayVisible(true)}
/>
</Tooltip>
{/* Form fields */}
<TextField
label="Item Name"
variant="outlined"
fullWidth
margin="normal"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={savingItem}
/> />
</Tooltip>
<TextField
label="Item Description"
variant="outlined"
fullWidth
margin="normal"
value={description}
onChange={(e) => setDescription(e.target.value)}
disabled={savingItem}
/>
{/* Box selection */}
{loadingBoxes ? (
<CircularProgress size={24} />
) : (
<select
value={selectedBoxId}
onChange={handleBoxChange}
disabled={savingItem}
>
<option value="">No box</option>
{boxes.map((box) => (
<option key={box.ID} value={box.ID}>
{box.name}
</option>
))}
</select>
)}
{/* Tags section */}
<Box sx={{ my: 2 }}>
<Typography variant="subtitle1" gutterBottom>Tags</Typography>
<TagManager
token={token}
itemId={item.ID}
initialTags={item.tags || []}
onTagsChange={handleTagsChange}
/>
</Box>
{/* Buttons */}
<Box sx={{ mt: 2 }}>
<Button
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR, mr: 1 }}
variant="contained"
component="label"
disabled={uploadingImage || savingItem}
>
{uploadingImage ? <CircularProgress size={24} /> : 'Upload Image'}
<input
type="file"
accept="image/*"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={(e) => setImagePath(e.target.files[0]?.name || '')}
/>
</Button>
<Button
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR, mr: 1 }}
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>
</Box>
</Box>
)} )}
{imageOverlayVisible && (
<div className="image-overlay">
<img src={imageSrc} alt={name} />
<button className="close-button" onClick={() => setImageOverlayVisible(false)}>
Close
</button>
</div>
)}
<TextField
label="Item Name"
variant="outlined"
fullWidth
margin="normal"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={savingItem}
/>
<TextField
label="Item Description"
variant="outlined"
fullWidth
margin="normal"
value={description}
onChange={(e) => setDescription(e.target.value)}
disabled={savingItem}
/>
{loadingBoxes ? (
<CircularProgress size={24} />
) : (
<select
value={selectedBoxId}
onChange={handleBoxChange}
disabled={savingItem}
>
<option value="">No box</option>
{boxes.map((box) => (
<option key={box.ID} value={box.ID}>
{box.name}
</option>
))}
</select>
)}
<br />
<br />
<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
type="file"
accept="image/*"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={(e) => setImagePath(e.target.files[0]?.name || '')}
/>
</Button>
<Button
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>
</Container> </Container>
); );
} }

View File

@ -19,7 +19,9 @@ import {
DialogActions, DialogActions,
Alert, Alert,
CircularProgress, CircularProgress,
Skeleton Chip,
Typography,
FormGroup
} 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 { useParams, useLocation } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
@ -27,6 +29,7 @@ import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall'; import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api'; import { api } from '../services/api';
import ItemDetails from './ItemDetails'; import ItemDetails from './ItemDetails';
import TagManager from './tagManager';
const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => ( const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
<TableRow> <TableRow>
@ -35,6 +38,20 @@ const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
</TableCell> </TableCell>
<TableCell>{item.name}</TableCell> <TableCell>{item.name}</TableCell>
<TableCell>{item.description}</TableCell> <TableCell>{item.description}</TableCell>
<TableCell>
{item.tags?.map(tag => (
<Chip
key={tag.ID}
label={tag.name}
size="small"
style={{
backgroundColor: tag.color,
color: '#fff',
margin: '0 2px'
}}
/>
))}
</TableCell>
<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">
@ -52,26 +69,6 @@ const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
</TableRow> </TableRow>
)); ));
const LoadingSkeleton = () => (
<TableRow>
<TableCell>
<Skeleton variant="circular" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton variant="text" width={100} />
</TableCell>
<TableCell>
<Skeleton variant="text" width="80%" />
</TableCell>
<TableCell>
<Box display="flex" gap={1}>
<Skeleton variant="circular" width={30} height={30} />
<Skeleton variant="circular" width={30} height={30} />
</Box>
</TableCell>
</TableRow>
);
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([]);
@ -79,31 +76,35 @@ export default function Items({ token }) {
const [newItemDescription, setNewItemDescription] = useState(''); const [newItemDescription, setNewItemDescription] = useState('');
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 || 'All Boxes';
const [itemImages, setItemImages] = useState({}); const [itemImages, setItemImages] = useState({});
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
const [openAddItemDialog, setOpenAddItemDialog] = useState(false); const [openAddItemDialog, setOpenAddItemDialog] = useState(false);
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [availableTags, setAvailableTags] = useState([]);
const [selectedTags, setSelectedTags] = useState([]);
const { execute: fetchItems, loading: loadingItems, error: itemsError } = useApiCall(); const { execute: fetchItems, loading: loadingItems, error: itemsError } = useApiCall();
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
const { execute: createItem, loading: creatingItem, error: createError } = useApiCall(); const { execute: createItem, loading: creatingItem, error: createError } = useApiCall();
const { execute: deleteItem, loading: deletingItem, error: deleteError } = useApiCall(); const { execute: deleteItem, loading: deletingItem, error: deleteError } = useApiCall();
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall(); const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
const url = boxId ? // Fetch items and tags on component mount
`${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxId}/items` :
`${process.env.REACT_APP_API_URL}/api/v1/items`;
useEffect(() => { useEffect(() => {
const getItems = async () => { const loadData = async () => {
try { try {
const response = await fetchItems(() => // Fetch items and tags in parallel
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token) const [itemsResponse, tagsResponse] = await Promise.all([
); fetchItems(() => boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)),
setItems(response.data); fetchTags(() => api.tags.getAll(token))
]);
setItems(itemsResponse.data);
setAvailableTags(tagsResponse.data);
// Fetch images for each item // Fetch images for each item
response.data.forEach(item => { itemsResponse.data.forEach(item => {
api.items.getImage(token, item.ID) api.items.getImage(token, item.ID)
.then(response => { .then(response => {
const reader = new FileReader(); const reader = new FileReader();
@ -124,29 +125,79 @@ export default function Items({ token }) {
}); });
} catch (err) {} } catch (err) {}
}; };
getItems(); loadData();
}, [token, boxId]); }, [token, boxId]);
const handleAddItem = () => { // Filter items based on search query and selected tags
setOpenAddItemDialog(true); const filteredItems = useMemo(() => {
return items.filter(item => {
// Text search match
const textMatch =
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(searchQuery.toLowerCase());
// Tag match - if no tags selected, show all items
const tagMatch = selectedTags.length === 0 ||
selectedTags.every(tagId =>
item.tags?.some(itemTag => itemTag.ID === tagId)
);
return textMatch && tagMatch;
});
}, [items, searchQuery, selectedTags]);
// Handle tag selection
const handleTagSelect = (tagId) => {
setSelectedTags(prev =>
prev.includes(tagId)
? prev.filter(id => id !== tagId)
: [...prev, tagId]
);
}; };
const handleCloseAddItemDialog = () => { // Rest of the component remains the same...
// (keeping all existing functions like handleAddItem, handleDeleteItem, etc.)
const handleAddItem = useCallback(() => {
setOpenAddItemDialog(true);
}, []);
const handleCloseAddItemDialog = useCallback(() => {
setOpenAddItemDialog(false); setOpenAddItemDialog(false);
setNewItemName(''); setNewItemName('');
setNewItemDescription(''); setNewItemDescription('');
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ''; fileInputRef.current.value = '';
} }
}; }, []);
const generateUniqueImageName = (imageName) => { const generateUniqueImageName = useCallback((imageName) => {
if (imageName.toLowerCase() === 'image.jpg') { if (imageName.toLowerCase() === 'image.jpg') {
const randomString = Math.random().toString(36).substr(2, 9); const randomString = Math.random().toString(36).substr(2, 9);
return `image_${randomString}.jpg`; return `image_${randomString}.jpg`;
} }
return imageName; return imageName;
}; }, []);
const handleDeleteItem = useCallback(async (itemId) => {
try {
await deleteItem(() => api.items.delete(token, itemId));
setItems(prev => prev.filter(item => item.ID !== itemId));
} catch (err) {}
}, [token, deleteItem]);
const handleEditItem = useCallback((item) => {
setEditingItem(item);
}, []);
const handleSaveEdit = useCallback(async () => {
setEditingItem(null);
// Refresh the items list after editing
try {
const response = await fetchItems(() =>
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
);
setItems(response.data);
} catch (err) {}
}, [token, boxId, fetchItems]);
const handleSaveNewItem = useCallback(async () => { const handleSaveNewItem = useCallback(async () => {
try { try {
@ -196,62 +247,62 @@ export default function Items({ token }) {
); );
setItems(response.data); setItems(response.data);
} catch (err) {} } catch (err) {}
}, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems]); }, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems, generateUniqueImageName]);
const handleDeleteItem = useCallback(async (itemId) => {
try {
await deleteItem(() => api.items.delete(token, itemId));
setItems(prev => prev.filter(item => item.ID !== itemId));
} catch (err) {}
}, [token, deleteItem]);
const handleEditItem = useCallback((item) => {
setEditingItem(item);
}, []);
const handleSaveEdit = async () => {
setEditingItem(null);
const response = await fetchItems(() =>
api.items.getAll(token, boxId)
);
setItems(response.data);
};
const filteredItems = useMemo(() =>
items.filter(item =>
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(searchQuery.toLowerCase())
),
[items, searchQuery]
);
return ( return (
<Container> <Container>
{(itemsError || createError || deleteError || uploadError) && ( {(itemsError || tagsError || createError || deleteError || uploadError) && (
<Alert severity="error" sx={{ mb: 2 }}> <Alert severity="error" sx={{ mb: 2 }}>
{itemsError?.message || createError?.message || deleteError?.message || uploadError?.message} {itemsError?.message || tagsError?.message || createError?.message ||
deleteError?.message || uploadError?.message}
</Alert> </Alert>
)} )}
<TextField <Box sx={{ mb: 3 }}>
label="Search" <TextField
variant="outlined" label="Search items..."
fullWidth variant="outlined"
margin="normal" fullWidth
value={searchQuery} margin="normal"
onChange={(e) => setSearchQuery(e.target.value)} value={searchQuery}
/> onChange={(e) => setSearchQuery(e.target.value)}
/>
<h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : `${boxName} (${items.length} items)`}</h2> <Box sx={{ mt: 2, mb: 2 }}>
<Typography variant="subtitle1" gutterBottom>Filter by tags:</Typography>
<Box display="flex" flexWrap="wrap" gap={1}>
{availableTags.map(tag => (
<Chip
key={tag.ID}
label={tag.name}
style={{
backgroundColor: selectedTags.includes(tag.ID) ? tag.color : 'transparent',
color: selectedTags.includes(tag.ID) ? '#fff' : 'inherit',
border: `1px solid ${tag.color}`
}}
onClick={() => handleTagSelect(tag.ID)}
clickable
/>
))}
</Box>
</Box>
</Box>
<Button <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} <Typography variant="h6">
variant="contained" {boxName === "All Boxes" ? "All Items" : `Items in ${boxName}`}
onClick={handleAddItem} ({filteredItems.length} items)
disabled={creatingItem} </Typography>
>
{creatingItem ? <CircularProgress size={24} /> : 'Add Item'} <Button
</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>
</Box>
<Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}> <Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}>
<DialogTitle>Add New Item</DialogTitle> <DialogTitle>Add New Item</DialogTitle>
@ -311,29 +362,23 @@ export default function Items({ token }) {
<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>Tags</TableCell>
<TableCell>Actions</TableCell> <TableCell>Actions</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{loadingItems ? ( {filteredItems.map((item) => (
[...Array(5)].map((_, i) => ( <Item
<LoadingSkeleton key={i} /> key={item.ID}
)) item={item}
) : ( itemImages={itemImages}
filteredItems.map((item) => ( onDelete={handleDeleteItem}
<Item onEdit={handleEditItem}
key={item.ID} />
item={item} ))}
itemImages={itemImages}
onDelete={handleDeleteItem}
onEdit={handleEditItem}
/>
))
)}
</TableBody> </TableBody>
</Table> </Table>
</TableContainer> </TableContainer>
)} )}
</Container> </Container>
); )};
}

View File

@ -0,0 +1,181 @@
import React, { useState, useEffect, useCallback } from 'react';
import {
Chip,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
Button,
Box,
CircularProgress,
Alert
} from '@mui/material';
import { LocalOffer as TagIcon } from '@mui/icons-material';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api';
const TagManager = React.memo(({ token, itemId, initialTags = [], onTagsChange }) => {
const [tags, setTags] = useState([]);
const [itemTags, setItemTags] = useState(initialTags);
const [openDialog, setOpenDialog] = useState(false);
const [newTagName, setNewTagName] = useState('');
const [newTagDescription, setNewTagDescription] = useState('');
const [newTagColor, setNewTagColor] = useState('#3366ff');
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
const { execute: createTag, loading: creatingTag, error: createError } = useApiCall();
const { execute: addTags, loading: addingTags, error: addError } = useApiCall();
const { execute: removeTag, loading: removingTag, error: removeError } = useApiCall();
// Only fetch tags once when component mounts
useEffect(() => {
const getTags = async () => {
try {
const response = await fetchTags(() => api.tags.getAll(token));
setTags(response.data);
} catch (err) {}
};
getTags();
}, []); // Empty dependency array - only run once on mount
// Update itemTags when initialTags prop changes
useEffect(() => {
setItemTags(initialTags);
}, [initialTags]);
const handleCreateTag = async () => {
try {
const response = await createTag(() => api.tags.create(token, {
name: newTagName,
description: newTagDescription,
color: newTagColor
}));
setTags(prevTags => [...prevTags, response.data]);
setOpenDialog(false);
setNewTagName('');
setNewTagDescription('');
setNewTagColor('#3366ff');
} catch (err) {}
};
const handleAddTag = async (tagId) => {
if (!itemId) return;
try {
await addTags(() => api.items.addTags(token, itemId, [tagId]));
const newTag = tags.find(t => t.ID === tagId);
if (newTag) {
const updatedTags = [...itemTags, newTag];
setItemTags(updatedTags);
onTagsChange?.(updatedTags);
}
} catch (err) {}
};
const handleRemoveTag = async (tagId) => {
if (!itemId) return;
try {
await removeTag(() => api.items.removeTag(token, itemId, tagId));
const updatedTags = itemTags.filter(tag => tag.ID !== tagId);
setItemTags(updatedTags);
onTagsChange?.(updatedTags);
} catch (err) {}
};
return (
<Box>
{(tagsError || createError || addError || removeError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{tagsError?.message || createError?.message ||
addError?.message || removeError?.message}
</Alert>
)}
<Box display="flex" alignItems="center" flexWrap="wrap" gap={1}>
{itemTags.map(tag => (
<Chip
key={tag.ID}
label={tag.name}
onDelete={() => handleRemoveTag(tag.ID)}
style={{
backgroundColor: tag.color,
color: '#fff'
}}
disabled={removingTag}
/>
))}
<Box sx={{ ml: 1 }}>
{loadingTags ? (
<CircularProgress size={24} />
) : (
tags
.filter(tag => !itemTags.find(it => it.ID === tag.ID))
.map(tag => (
<Chip
key={tag.ID}
label={tag.name}
onClick={() => handleAddTag(tag.ID)}
style={{
backgroundColor: tag.color,
color: '#fff',
margin: '0 4px'
}}
disabled={addingTags}
/>
))
)}
</Box>
<Button
startIcon={<TagIcon />}
variant="outlined"
size="small"
onClick={() => setOpenDialog(true)}
sx={{ ml: 1 }}
>
New Tag
</Button>
</Box>
<Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
<DialogTitle>Create New Tag</DialogTitle>
<DialogContent>
<TextField
label="Name"
value={newTagName}
onChange={(e) => setNewTagName(e.target.value)}
fullWidth
margin="normal"
/>
<TextField
label="Description"
value={newTagDescription}
onChange={(e) => setNewTagDescription(e.target.value)}
fullWidth
margin="normal"
/>
<TextField
label="Color"
type="color"
value={newTagColor}
onChange={(e) => setNewTagColor(e.target.value)}
fullWidth
margin="normal"
/>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpenDialog(false)}>Cancel</Button>
<Button
onClick={handleCreateTag}
disabled={creatingTag || !newTagName.trim()}
>
{creatingTag ? <CircularProgress size={24} /> : 'Create'}
</Button>
</DialogActions>
</Dialog>
</Box>
);
});
export default TagManager;

View File

@ -0,0 +1,134 @@
import React from 'react';
import { createTheme, ThemeProvider, CssBaseline } from '@mui/material';
import { grey, blue } from '@mui/material/colors';
// Enhanced theme with better visual hierarchy and modern styling
const theme = createTheme({
palette: {
mode: 'light',
primary: {
main: blue[700],
dark: blue[900],
light: blue[500],
contrastText: '#fff'
},
background: {
default: grey[100],
paper: '#fff'
}
},
typography: {
h1: {
fontSize: '2.5rem',
fontWeight: 600,
marginBottom: '1.5rem'
},
h2: {
fontSize: '2rem',
fontWeight: 500,
marginBottom: '1.25rem'
},
h3: {
fontSize: '1.75rem',
fontWeight: 500,
marginBottom: '1rem'
}
},
components: {
MuiButton: {
styleOverrides: {
root: {
textTransform: 'none',
borderRadius: 8,
padding: '8px 16px',
fontWeight: 500
},
contained: {
boxShadow: 'none',
'&:hover': {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}
}
}
},
MuiCard: {
styleOverrides: {
root: {
borderRadius: 12,
boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
'&:hover': {
boxShadow: '0 4px 12px rgba(0,0,0,0.12)'
}
}
}
},
MuiTextField: {
styleOverrides: {
root: {
'& .MuiOutlinedInput-root': {
borderRadius: 8,
backgroundColor: '#fff',
'&:hover fieldset': {
borderColor: blue[400]
}
}
}
}
},
MuiTable: {
styleOverrides: {
root: {
backgroundColor: '#fff',
borderRadius: 12,
overflow: 'hidden'
}
}
},
MuiTableHead: {
styleOverrides: {
root: {
backgroundColor: grey[50]
}
}
},
MuiTableCell: {
styleOverrides: {
head: {
fontWeight: 600,
color: grey[900]
}
}
}
}
});
// Layout component for consistent padding and max-width
const Layout = ({ children }) => (
<div className="p-6 max-w-7xl mx-auto">
{children}
</div>
);
// Enhanced page container with proper spacing and background
const PageContainer = ({ children, title }) => (
<div className="min-h-screen bg-gray-100">
<Layout>
{title && <h1 className="text-3xl font-semibold mb-6">{title}</h1>}
<div className="bg-white rounded-xl shadow-sm p-6">
{children}
</div>
</Layout>
</div>
);
export function EnhancedThemeProvider({ children }) {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
}
export { Layout, PageContainer };
export default EnhancedThemeProvider;

View File

@ -36,8 +36,15 @@ const createApiClient = () => {
}), }),
getByBox: (token, boxId) => getByBox: (token, boxId) =>
client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }), client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }),
addTags: (token, itemId, tagIds) =>
client.post(`/api/v1/items/${itemId}/tags`, tagIds, {
headers: authHeader(token)
}),
removeTag: (token, itemId, tagId) =>
client.delete(`/api/v1/items/${itemId}/tags/${tagId}`, {
headers: authHeader(token)
}),
}, },
// Boxes // Boxes
boxes: { boxes: {
getAll: (token) => getAll: (token) =>
@ -48,6 +55,19 @@ const createApiClient = () => {
client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }), client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }),
}, },
tags: {
getAll: (token) =>
client.get('/api/v1/tags', { headers: authHeader(token) }),
create: (token, tagData) =>
client.post('/api/v1/tags', tagData, { headers: authHeader(token) }),
update: (token, id, tagData) =>
client.put(`/api/v1/tags/${id}`, tagData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/tags/${id}`, { headers: authHeader(token) }),
getItems: (token, id) =>
client.get(`/api/v1/tags/${id}/items`, { headers: authHeader(token) }),
},
// Admin // Admin
admin: { admin: {
getUsers: (token) => getUsers: (token) =>

View File

@ -1,6 +1,5 @@
// src/services/errorHandler.js // src/utils/errorHandler.js
import axios from 'axios'; import axios from 'axios';
import { jwtDecode } from 'jwt-decode';
export class ApiError extends Error { export class ApiError extends Error {
constructor(message, status, details = {}) { constructor(message, status, details = {}) {
@ -8,89 +7,30 @@ export class ApiError extends Error {
this.status = status; this.status = status;
this.details = details; this.details = details;
} }
} }
export const createApiClient = () => { // Enhanced API client with error handling
const client = axios.create({ export const createApiClient = () => {
baseURL: process.env.REACT_APP_API_URL, const client = axios.create({
headers: { baseURL: process.env.REACT_APP_API_URL
'X-Content-Type-Options': 'nosniff', });
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block'
}
});
// Add request interceptor for token validation client.interceptors.response.use(
client.interceptors.request.use(async (config) => { response => response,
const token = localStorage.getItem('token'); error => {
if (!token) return config; if (error.response?.status === 401) {
try {
const decodedToken = jwtDecode(token);
const currentTime = Date.now() / 1000;
if (decodedToken.exp < currentTime) {
localStorage.removeItem('token');
window.location.href = '/api/v1/login';
throw new ApiError('Session expired', 401);
}
// Refresh token if expiring soon
if (decodedToken.exp - currentTime < 300) {
try {
const response = await axios.post('/api/v1/refresh-token', { token });
localStorage.setItem('token', response.data.token);
config.headers.Authorization = `Bearer ${response.data.token}`;
} catch (error) {
localStorage.removeItem('token'); localStorage.removeItem('token');
window.location.href = '/api/v1/login'; window.location.href = '/login';
throw new ApiError('Failed to refresh token', 401); 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
));
} }
);
config.headers.Authorization = `Bearer ${token}`; return client;
} catch (error) { };
localStorage.removeItem('token');
window.location.href = '/api/v1/login';
throw new ApiError('Invalid token', 401);
}
// Add CSRF token if available
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
if (csrfToken) {
config.headers['X-CSRF-Token'] = csrfToken;
}
return config;
});
// Enhanced response interceptor
client.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
window.location.href = '/api/v1/login';
return Promise.reject(new ApiError('Session expired', 401));
}
// Handle rate limiting
if (error.response?.status === 429) {
return Promise.reject(new ApiError('Too many requests. Please try again later.', 429));
}
// Handle server errors
if (error.response?.status >= 500) {
return Promise.reject(new ApiError('Server error. Please try again later.', error.response.status));
}
return Promise.reject(new ApiError(
error.response?.data?.message || 'An error occurred',
error.response?.status,
error.response?.data
));
}
);
return client;
};