GUI improvements

This commit is contained in:
Steve White 2024-11-01 23:47:37 -05:00
parent 74502b1077
commit e0f7af5e88
3 changed files with 345 additions and 205 deletions

View File

@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
// import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import './Admin.css';
@ -19,33 +19,41 @@ import {
Container,
Box,
TextField,
CircularProgress
CircularProgress,
Tab,
Tabs
} from '@mui/material';
export default function Admin() {
const [users, setUsers] = useState([]);
const [tags, setTags] = useState([]);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [activeTab, setActiveTab] = useState(0);
const navigate = useNavigate();
const fileInputRef = useRef(null);
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: deleteUser, loading: deletingUser, error: deleteError } = useApiCall();
const { execute: deleteTag, loading: deletingTag, error: deleteTagError } = useApiCall();
const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall();
const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall();
useEffect(() => {
const getUsers = async () => {
const getInitialData = async () => {
try {
const response = await fetchUsers(() =>
api.admin.getUsers(localStorage.getItem('token'))
);
setUsers(response.data);
const [usersResponse, tagsResponse] = await Promise.all([
fetchUsers(() => api.admin.getUsers(localStorage.getItem('token'))),
fetchTags(() => api.tags.getAll(localStorage.getItem('token')))
]);
setUsers(usersResponse.data);
setTags(tagsResponse.data);
} catch (err) {}
};
getUsers();
getInitialData();
}, []);
const handleCreateUser = async (e) => {
@ -73,6 +81,19 @@ export default function Admin() {
} 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 () => {
try {
const response = await backupDB(() =>
@ -109,113 +130,180 @@ export default function Admin() {
Admin Dashboard
</Typography>
{(usersError || createError || deleteError || backupError || restoreError) && (
{(usersError || createError || deleteError || backupError || restoreError || tagsError || deleteTagError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{usersError?.message || createError?.message || deleteError?.message ||
backupError?.message || restoreError?.message}
backupError?.message || restoreError?.message || tagsError?.message || deleteTagError?.message}
</Alert>
)}
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
<Typography variant="h6" gutterBottom>
Add New User
</Typography>
<TextField
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 ? (
<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>
<Tabs value={activeTab} onChange={(e, newValue) => setActiveTab(newValue)} sx={{ mb: 3 }}>
<Tab label="Users" />
<Tab label="Tags" />
<Tab label="Database" />
</Tabs>
{activeTab === 0 && (
<>
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
<Typography variant="h6" gutterBottom>
Add New User
</Typography>
<TextField
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 ? (
<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 }}>
<Button
variant="contained"
onClick={handleBackupDatabase}
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
disabled={backingUp}
>
{backingUp ? <CircularProgress size={24} /> : 'Backup Database'}
</Button>
{activeTab === 1 && (
<>
<Typography variant="h6" gutterBottom>
Manage Tags
</Typography>
{loadingTags ? (
<CircularProgress />
) : (
<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
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>
{activeTab === 2 && (
<Box sx={{ mt: 4 }}>
<Typography variant="h6" gutterBottom>
Database Management
</Typography>
<Button
variant="contained"
onClick={handleBackupDatabase}
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
disabled={backingUp}
>
{backingUp ? <CircularProgress size={24} /> : 'Backup Database'}
</Button>
<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>
);
}

View File

@ -19,7 +19,9 @@ import {
DialogActions,
Alert,
CircularProgress,
Chip
Chip,
Typography,
FormGroup
} from '@mui/material';
import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material';
import { useParams, useLocation } from 'react-router-dom';
@ -29,8 +31,6 @@ import { api } from '../services/api';
import ItemDetails from './ItemDetails';
import TagManager from './tagManager';
// In Items.js, modify the Item component
const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
<TableRow>
<TableCell>
@ -38,7 +38,7 @@ const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.description}</TableCell>
<TableCell> {/* Add this cell */}
<TableCell>
{item.tags?.map(tag => (
<Chip
key={tag.ID}
@ -76,31 +76,35 @@ export default function Items({ token }) {
const [newItemDescription, setNewItemDescription] = useState('');
const [editingItem, setEditingItem] = useState(null);
const location = useLocation();
const boxName = location.state?.boxName || 'Unknown Box';
const boxName = location.state?.boxName || 'All Boxes';
const [itemImages, setItemImages] = useState({});
const fileInputRef = useRef(null);
const [openAddItemDialog, setOpenAddItemDialog] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [availableTags, setAvailableTags] = useState([]);
const [selectedTags, setSelectedTags] = useState([]);
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: deleteItem, loading: deletingItem, error: deleteError } = useApiCall();
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
const url = boxId ?
`${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxId}/items` :
`${process.env.REACT_APP_API_URL}/api/v1/items`;
// Fetch items and tags on component mount
useEffect(() => {
const getItems = async () => {
const loadData = async () => {
try {
const response = await fetchItems(() =>
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
);
setItems(response.data);
// Fetch items and tags in parallel
const [itemsResponse, tagsResponse] = await Promise.all([
fetchItems(() => boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)),
fetchTags(() => api.tags.getAll(token))
]);
setItems(itemsResponse.data);
setAvailableTags(tagsResponse.data);
// Fetch images for each item
response.data.forEach(item => {
itemsResponse.data.forEach(item => {
api.items.getImage(token, item.ID)
.then(response => {
const reader = new FileReader();
@ -121,30 +125,80 @@ export default function Items({ token }) {
});
} catch (err) {}
};
getItems();
loadData();
}, [token, boxId]);
const handleAddItem = () => {
setOpenAddItemDialog(true);
// Filter items based on search query and selected tags
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);
setNewItemName('');
setNewItemDescription('');
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
}, []);
const generateUniqueImageName = (imageName) => {
const generateUniqueImageName = useCallback((imageName) => {
if (imageName.toLowerCase() === 'image.jpg') {
const randomString = Math.random().toString(36).substr(2, 9);
return `image_${randomString}.jpg`;
}
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 () => {
try {
const newItemResponse = await createItem(() =>
@ -193,66 +247,63 @@ export default function Items({ token }) {
);
setItems(response.data);
} catch (err) {}
}, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems]);
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);
// 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) {}
};
const filteredItems = useMemo(() =>
items.filter(item =>
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(searchQuery.toLowerCase())
),
[items, searchQuery]
);
}, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems, generateUniqueImageName]);
return (
<Container>
{(itemsError || createError || deleteError || uploadError) && (
{(itemsError || tagsError || createError || deleteError || uploadError) && (
<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>
)}
<TextField
label="Search"
variant="outlined"
fullWidth
margin="normal"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : `${boxName} (${items.length} items)`}</h2>
<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 sx={{ mb: 3 }}>
<TextField
label="Search items..."
variant="outlined"
fullWidth
margin="normal"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<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>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6">
{boxName === "All Boxes" ? "All Items" : `Items in ${boxName}`}
({filteredItems.length} items)
</Typography>
<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}>
<DialogTitle>Add New Item</DialogTitle>
<DialogContent>
@ -290,7 +341,7 @@ export default function Items({ token }) {
</Button>
</DialogActions>
</Dialog>
{editingItem && (
<ItemDetails
item={editingItem}
@ -300,7 +351,7 @@ export default function Items({ token }) {
boxId={boxId}
/>
)}
{loadingItems ? (
<CircularProgress />
) : (
@ -315,20 +366,19 @@ export default function Items({ token }) {
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{filteredItems.map((item) => (
<Item
key={item.ID}
item={item}
itemImages={itemImages}
onDelete={handleDeleteItem}
onEdit={handleEditItem}
/>
))}
</TableBody>
<TableBody>
{filteredItems.map((item) => (
<Item
key={item.ID}
item={item}
itemImages={itemImages}
onDelete={handleDeleteItem}
onEdit={handleEditItem}
/>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Container>
);
}
)};

View File

@ -27,11 +27,7 @@ const createApiClient = () => {
client.delete(`/api/v1/items/${id}`, { headers: authHeader(token) }),
uploadImage: (token, id, formData) =>
client.post(`/api/v1/items/${id}/upload`, formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' },
addTags: (token, id, tagIds) =>
client.post(`/api/v1/items/${id}/tags`, tagIds, { headers: authHeader(token) }),
removeTag: (token, id, tagId) =>
client.delete(`/api/v1/items/${id}/tags/${tagId}`, { headers: authHeader(token) }),
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
getImage: (token, id) =>
client.get(`/api/v1/items/${id}/image`, {
@ -40,8 +36,15 @@ const createApiClient = () => {
}),
getByBox: (token, boxId) =>
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: {
getAll: (token) =>
@ -64,7 +67,6 @@ const createApiClient = () => {
getItems: (token, id) =>
client.get(`/api/v1/tags/${id}/items`, { headers: authHeader(token) }),
},
// Admin
admin: {