Compare commits

...

25 Commits

Author SHA1 Message Date
Steve White c400ccc400 Merge pull request 'error-handling' (#1) from error-handling into main
Reviewed-on: #1
2024-10-30 15:19:48 +00:00
Steve White efa24c3f84 Added errorboundary, memoized items for performance. 2024-10-30 10:17:52 -05:00
Steve White 2e598968ac refactored error-handling application-wide. Also improved itemdetails display somehow, accidentally. 2024-10-30 09:36:32 -05:00
Steve White 165e4965df refactored to use consistent api access via api.js 2024-10-30 08:57:41 -05:00
Steve White bd32bfaae5 Fixing build system 2024-10-29 19:41:34 -05:00
Steve White 31eb7c0439 attempting to reload /index with any user-generated reload 2024-10-29 13:20:42 -05:00
Steve White 158d52dab4 Changes app name to Boxes instead of React App 2024-10-24 15:51:36 -05:00
Steve White ca301c3108 Updated README.md with Docker instrauciotns 2024-10-23 13:03:34 -05:00
Steve White 5f3b592724 Added a bunch of Docker crap but I think Dockerfile.build is all that matters 2024-10-23 12:49:43 -05:00
Steve White 3f33d5fda4 Changed api endpoints to include /api/v1 2024-10-21 11:27:57 -05:00
Steve White 67a1b82442 Merge branch 'ChatGPT' of gitea.r8z.us:stwhite/boxes-fe into ChatGPT 2024-10-21 11:03:17 -05:00
Steve White 7b1184c81d made the boxes table smaller 2024-10-19 12:44:36 -05:00
Steve White a48f96f143 made changes at both ends.
Merge branch 'ChatGPT' of gitea.r8z.us:stwhite/boxes-fe into ChatGPT
2024-10-19 12:43:51 -05:00
Steve White aae9a189a8 moved .env and added code to print REACT_APP_API_URL 2024-10-18 12:30:31 -05:00
Steve White 45932d4af2 fixed delete boxes 2024-10-17 20:53:09 -05:00
Steve White a7e89a8f2b added dockerfile 2024-10-17 10:45:32 -05:00
Steve White 4998f3a2d5 Fixing MaterialUI stuff 2024-10-17 10:43:58 -05:00
Steve White 578d38f187 More UI fixes to Admin.js 2024-10-17 09:04:28 -05:00
Steve White 88a90e39b7 UI cleanup with tables and chairs and tooltips :D 2024-10-17 08:47:27 -05:00
Steve White cd394ca1ee Admin page added - create/delete users, backup and restore database 2024-10-17 08:11:58 -05:00
Steve White 487aa5154e User and database administration 2024-10-17 00:08:41 -05:00
Steve White ff6b9be749 added some verbose comments 2024-10-15 17:04:04 -05:00
Steve White ea690d14c6 added type-down search 2024-10-15 16:27:11 -05:00
Steve White 8424579dcb fixed item box selection 2024-10-14 23:55:43 -05:00
Steve White 02aca14e95 Trying to get the box update code to work. 2024-10-14 09:41:46 -05:00
24 changed files with 1039 additions and 517 deletions

5
.dockerignore Normal file
View File

@ -0,0 +1,5 @@
node_modules
.git
*.log
build
.DS_Store

3
.env
View File

@ -1 +1,2 @@
REACT_APP_API_URL=http://127.0.0.1:8080 REACT_APP_API_URL=http://nebula1:8080

7
Dockerfile Normal file
View File

@ -0,0 +1,7 @@
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY .env .
COPY . .
CMD ["npm", "run", "build"]

23
Dockerfile.build Normal file
View File

@ -0,0 +1,23 @@
# Stage 1: Install dependencies
FROM node:14 AS build-stage
WORKDIR /app
# Copy package.json and package-lock.json first to leverage caching
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of your application code
COPY .env .
COPY . .
# Build the application
RUN npm run build
# Final stage: Use a minimal base image
FROM alpine:latest
# Copy the build output from the previous stage
COPY --from=build-stage /app/build ./build

20
Dockerfile.create Normal file
View File

@ -0,0 +1,20 @@
# Dockerfile.create
FROM node:14 AS builder
# Set working directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
RUN npm install -g serve
# Copy the rest of the application code
COPY . .
COPY .env .
RUN npm build .
CMD ["serve", "-s", "build"]

4
Dockerfile.nginx Normal file
View File

@ -0,0 +1,4 @@
FROM nginx:alpine
COPY build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

18
Dockerfile.update Normal file
View File

@ -0,0 +1,18 @@
# Dockerfile.update
FROM node:14
# Set working directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
ENV REACT_APP_API_URL=http://zbox.local:8080
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
COPY .env .
CMD ["npm", "run", "build"]

View File

@ -27,3 +27,21 @@ This is the frontend application for the Boxes App, built with React. It allows
1. **Clone the repository:** 1. **Clone the repository:**
```bash ```bash
git clone git@gitea.r8z.us:stwhite/boxes-fe.git git clone git@gitea.r8z.us:stwhite/boxes-fe.git
2. create the docker builder
```bash
docker build -f Dockerfile.build -t boxes-fe-builder .
```
3. build the application using the docker builder
```bash
docker run box-builder:latest
docker container create --name tmp-con boxes-fe-builder -- sleep 1200
docker cp tmp-con:/app/build ./boxes-fe/build
docker rm tmp-con
```
4. copy the appliction to the boxes-api /build directory
```bash
cp -r ./boxes-fe/build/* ../boxes-api/build/
```

7
build.bash Executable file
View File

@ -0,0 +1,7 @@
#!/bin/bash
# Create teh react-builder image
docker build -f Dockerfile.create -t react-builder:latest .
# Run the react-builder image with local build/ dir mounted
docker run -v $(pwd)/build:/app/build react-builder:latest
# create the nginx container:
docker build --no-cache -f Dockerfile.nginx -t boxes-fe:latest .

View File

@ -24,7 +24,7 @@
work correctly both with client-side routing and a non-root public URL. work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`. Learn how to configure a non-root public URL by running `npm run build`.
--> -->
<title>React App</title> <title>Boxes</title>
</head> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>

View File

@ -6,7 +6,9 @@ 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'; // Correct import here import Navbar from './components/Navbar'; // Correct import here
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'
export const AppContext = createContext(); export const AppContext = createContext();
@ -25,10 +27,12 @@ function App() {
return ( return (
<AppContext.Provider value={{ token, setToken }}> <AppContext.Provider value={{ token, setToken }}>
<ErrorBoundary>
<Router> <Router>
<Navbar /> <Navbar />
<AppRoutes token={token} setToken={setToken} /> <AppRoutes token={token} setToken={setToken} />
</Router> </Router>
</ErrorBoundary>
</AppContext.Provider> </AppContext.Provider>
); );
} }
@ -39,20 +43,24 @@ function AppRoutes({ token, setToken }) {
return ( return (
<> <>
<Routes> <Routes>
<Route path="/login" element={<Login setToken={setToken} />} /> <Route path="/api/v1/login" element={<Login setToken={setToken} />} />
<Route <Route
path="/boxes" path="/api/v1/boxes"
element={token ? <Boxes token={token} /> : <Navigate to="/login" replace />} element={token ? <Boxes token={token} /> : <Navigate to="/api/v1/login" replace />}
/> />
<Route <Route
path="/items" path="/api/v1/items"
element={token ? <Items token={token} /> : <Navigate to="/login" replace />} element={token ? <Items token={token} /> : <Navigate to="/api/v1/login" replace />}
/> />
<Route <Route
path="/boxes/:id/items" path="/api/v1/boxes/:id/items"
element={token ? <Items box_id={id} token={token} /> : <Navigate to="/login" replace />} element={token ? <Items box_id={id} token={token} /> : <Navigate to="/api/v1/login" replace />}
/> />
<Route path="*" element={<Navigate to={token ? "/boxes" : "/login"} replace />} /> <Route
path="/api/v1/admin"
element={token ? <Admin token={token}/> : <Navigate to="/api/v1/login" replace />}
/>
<Route path="*" element={<Navigate to={token ? "/api/v1/boxes" : "/api/v1/login"} replace />} />
</Routes> </Routes>
</> </>
); );

15
src/components/Admin.css Normal file
View File

@ -0,0 +1,15 @@
/* Admin.css */
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 10px;
text-align: left;
}
th {
background-color: #f0f0f0;
}

221
src/components/Admin.js Normal file
View File

@ -0,0 +1,221 @@
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import './Admin.css';
import { useApiCall } from './hooks/useApiCall';
import { api } from '../services/api';
import {
Typography,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Button,
Alert,
Container,
Box,
TextField,
CircularProgress
} from '@mui/material';
export default function Admin() {
const [users, setUsers] = useState([]);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const fileInputRef = useRef(null);
const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall();
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();
useEffect(() => {
const getUsers = async () => {
try {
const response = await fetchUsers(() =>
api.admin.getUsers(localStorage.getItem('token'))
);
setUsers(response.data);
} catch (err) {}
};
getUsers();
}, []);
const handleCreateUser = async (e) => {
e.preventDefault();
try {
const response = await createUser(() =>
api.admin.createUser(
localStorage.getItem('token'),
{ username, password, email }
)
);
setUsers([...users, response.data]);
setUsername('');
setPassword('');
setEmail('');
} catch (err) {}
};
const handleDeleteUser = async (id) => {
try {
await deleteUser(() =>
api.admin.deleteUser(localStorage.getItem('token'), id)
);
setUsers(users.filter(user => user.id !== id));
} catch (err) {}
};
const handleBackupDatabase = async () => {
try {
const response = await backupDB(() =>
api.admin.backupDB(localStorage.getItem('token'))
);
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'database.db';
a.click();
} catch (err) {}
};
const handleRestoreDatabase = async (e) => {
e.preventDefault();
if (!fileInputRef.current?.files?.[0]) return;
try {
const formData = new FormData();
formData.append('database', fileInputRef.current.files[0]);
await restoreDB(() =>
api.admin.restoreDB(localStorage.getItem('token'), formData)
);
alert('Database restored successfully');
navigate('/admin');
} catch (err) {}
};
return (
<Container maxWidth="md">
<Typography variant="h4" gutterBottom>
Admin Dashboard
</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 }}>
<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>
<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

@ -1,83 +1,123 @@
// src/components/Boxes.js
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Container, Button, TextField, List, ListItem, ListItemText, IconButton } 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 axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { useApiCall } from './hooks/useApiCall';
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('');
const apiUrl = `${process.env.REACT_APP_API_URL}/boxes`;
const debugApi = () => { const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
if (process.env.DEBUG_API) { const { execute: createBox, loading: creatingBox, error: createError } = useApiCall();
console.log("URL is " + apiUrl); const { execute: deleteBox, loading: deletingBox, error: deleteError } = useApiCall();
}
};
debugApi();
useEffect(() => { useEffect(() => {
//console.log('Token:' + token); const getBoxes = async () => {
axios.get(`${process.env.REACT_APP_API_URL}/boxes`, { try {
headers: { Authorization: `Bearer ${token}` } const response = await fetchBoxes(() =>
}).then(response => { api.boxes.getAll(token)
);
setBoxes(response.data); setBoxes(response.data);
}); } catch (err) {}
}, [token]); };
getBoxes();
}, [token]); // Remove fetchBoxes from dependencies
// Log boxes state changes outside the useEffect const handleCreateBox = async () => {
useEffect(() => { if (!newBoxName.trim()) return;
//console.log('Boxes updated:', boxes);
}, [boxes]);
const handleCreateBox = () => { try {
axios.post(`${process.env.REACT_APP_API_URL}/boxes`, { name: newBoxName }, { const response = await createBox(() =>
headers: { Authorization: `Bearer ${token}` } api.boxes.create(token, { name: newBoxName })
}).then(response => { );
setBoxes([...boxes, response.data]); setBoxes([...boxes, response.data]);
setNewBoxName(''); setNewBoxName('');
}); } catch (err) {}
}; };
const handleDeleteBox = (id) => { const handleDeleteBox = async (id) => {
axios.delete(`${process.env.REACT_APP_API_URL}/boxes/${id}`, { try {
headers: { Authorization: `Bearer ${token}` } await deleteBox(() =>
}).then(() => { api.boxes.delete(token, id)
setBoxes(boxes.filter(box => box.id !== id)); );
}); setBoxes(boxes.filter(box => box.ID !== id));
} catch (err) {}
}; };
return ( return (
<Container> <Container>
{(boxesError || createError || deleteError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{boxesError?.message || createError?.message || deleteError?.message}
</Alert>
)}
{loadingBoxes ? (
<CircularProgress />
) : (
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Box Name</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{boxes.map((box) => (
<TableRow key={box.ID}>
<TableCell>
<RouterLink to={`/api/v1/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}>
{box.name}
</RouterLink>
</TableCell>
<TableCell>
<Button
onClick={() => handleDeleteBox(box.ID)}
startIcon={<DeleteIcon />}
disabled={deletingBox}
>
{deletingBox ? <CircularProgress size={20} /> : 'Delete'}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
<TextField <TextField
label="New Box" label="New Box"
variant="outlined" variant="outlined"
fullWidth fullWidth
value={newBoxName} value={newBoxName}
onChange={(e) => setNewBoxName(e.target.value)} onChange={(e) => setNewBoxName(e.target.value)}
disabled={creatingBox}
/> />
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleCreateBox}> <Button
Add Box sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={handleCreateBox}
disabled={creatingBox || !newBoxName.trim()}
>
{creatingBox ? <CircularProgress size={24} /> : 'Add Box'}
</Button> </Button>
<List>
{boxes.map((box) => (
<ListItem key={box.ID} secondaryAction={
<IconButton edge="end" onClick={() => handleDeleteBox(box.ID)}>
<DeleteIcon />
</IconButton>
}>
<ListItemText
primary={
<RouterLink to={`/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}> {/* Use Link component */}
{box.name}
</RouterLink>
}
/>
</ListItem>
))}
</List>
</Container> </Container>
); );
} }

View File

@ -0,0 +1,36 @@
import React from 'react';
import { Alert, Button, Container } from '@mui/material';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
render() {
if (this.state.hasError) {
return (
<Container>
<Alert severity="error" sx={{ mt: 2 }}>
Something went wrong
<Button
onClick={() => window.location.reload()}
variant="outlined"
size="small"
sx={{ ml: 2 }}
>
Reload Page
</Button>
</Alert>
</Container>
);
}
return this.props.children;
}
}
export default ErrorBoundary;

View File

@ -1,187 +1,123 @@
// src/components/ItemDetails.js
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { TextField, Button, Container, Avatar, Typography } from '@mui/material'; import { TextField, Button, Container, Avatar, Tooltip, Alert, CircularProgress } from '@mui/material';
import axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
//import { useNavigate } from 'react-router-dom'; // Import useNavigate import { useApiCall } from './hooks/useApiCall';
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'); // Initial default image const [imageSrc, setImageSrc] = useState('/images/default.jpg');
const fileInputRef = useRef(null); // Add this line to define fileInputRef const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fileInputRef = useRef(null);
const [imageOverlayVisible, setImageOverlayVisible] = useState(false); const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
// const navigate = useNavigate(); // Initialize useNavigate
const [boxName, setBoxName] = useState('');
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [selectedBoxId, setSelectedBoxId] = useState(boxId); 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 axios.get(`${process.env.REACT_APP_API_URL}/boxes`, { const response = await fetchBoxes(() => api.boxes.getAll(token));
headers: { Authorization: `Bearer ${token}` }
});
setBoxes(response.data); setBoxes(response.data);
} catch (error) { } catch (err) {}
console.error('Error fetching boxes:', error);
}
}; };
fetchBoxes(); getBoxes();
}, [token]); }, [token]);
const handleBoxChange = (event) => {
setSelectedBoxId(event.target.value);
console.log('Selected box ID:', event.target.value);
};
useEffect(() => { useEffect(() => {
// Function to fetch box details const loadImage = async () => {
const getBoxDetails = async (boxId) => { setLoading(true);
setError(null);
try { try {
const boxIdNumber = +boxId; const response = await api.items.getImage(token, item.ID);
if (isNaN(boxIdNumber)) {
console.error('Invalid boxId:', boxId);
return;
}
const response = await axios.get(`${process.env.REACT_APP_API_URL}/boxes/${+boxId}`, {
headers: { Authorization: `Bearer ${token}` }
});
setBoxName(response.data.name);
} catch (error) {
console.error('Error fetching box details:', error);
}
};
// Fetch the box details when the component mounts or the selectedBoxId changes
if (selectedBoxId !== null) {
getBoxDetails(selectedBoxId);
}
}, [selectedBoxId, token, boxId]);
useEffect(() => {
// Function to fetch image similar to getImageSrc in Items.js
const getImageSrc = (itemId) => {
return axios.get(`${process.env.REACT_APP_API_URL}/items/${itemId}/image`, {
headers: { Authorization: `Bearer ${token}` },
responseType: 'blob'
})
.then(response => {
if (response.status === 200) {
return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => resolve(reader.result); reader.onload = () => {
reader.onerror = reject; setImageSrc(reader.result);
setLoading(false);
};
reader.readAsDataURL(response.data); reader.readAsDataURL(response.data);
}); } catch (err) {
} else { setImageSrc('/default.jpg');
throw new Error('Image fetch failed'); setError(err);
setLoading(false);
} }
})
.catch(() => {
// Return the data URL of the default image if image fetch fails
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);
const dataURL = canvas.toDataURL();
resolve(dataURL);
}; };
img.onerror = reject; loadImage();
});
});
};
// Fetch the image when the component mounts or the item changes
getImageSrc(item.ID).then(dataUrl => setImageSrc(dataUrl));
}, [item.ID, token]); }, [item.ID, token]);
// const handleCloseItemDetails = () => {
// onClose(); // Call the onClose prop to close the modal
// navigate(`/boxes/${boxId}/items`); // Navigate back to the items list
// };
const handleImageUpload = async () => { const handleImageUpload = async () => {
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 axios.post(`${process.env.REACT_APP_API_URL}/items/${item.ID}/upload`, formData, { const response = await uploadImage(() =>
headers: { api.items.uploadImage(token, item.ID, formData)
Authorization: `Bearer ${token}`, );
'Content-Type': 'multipart/form-data' return response.data.imagePath;
} } catch (err) {
}); return null;
// Handle successful upload (e.g., show a success message)
console.log('Image uploaded successfully!', response.data.imagePath);
return response.data.imagePath; // Indicate successful upload
} catch (error) {
// Handle upload error (e.g., show an error message)
console.error('Image upload failed:', error);
} }
}; };
const handleSave = async () => { const handleSave = async () => {
let imagePath; if (fileInputRef.current?.files?.[0]) {
// 1. Handle image upload first if a new image is selected await handleImageUpload();
if (fileInputRef.current.files[0]) {
imagePath = await handleImageUpload();
} }
console.log(selectedBoxId)
// 2. Update item details (name, description, etc.)
try { try {
await axios.put(`${process.env.REACT_APP_API_URL}/items/${item.ID}`, await updateItem(() => api.items.update(token, item.ID, {
{ name, description, image_path: imagePath, BoxID: selectedBoxId }, // Use teh uploaded image path name,
{ description,
headers: { Authorization: `Bearer ${token}` } box_id: +selectedBoxId,
} }));
); onSave();
onSave(); // Notify parent to refresh items } catch (err) {}
} catch (error) {
// Handle update error
console.error('Item update failed:', error);
}
}; };
const handleImageError = (e) => { const handleBoxChange = (event) => {
e.target.src = '/images/default.jpg'; // Fallback to default image on error setSelectedBoxId(event.target.value);
};
const handleAvatarClick = () => {
setImageOverlayVisible(true);
};
const handleCloseOverlay = () => {
setImageOverlayVisible(false);
}; };
return ( return (
<Container> <Container>
<h3>Edit Item: {item.name}</h3> <h3>Edit Item: {item.name}</h3>
{/* Display the item image as an avatar */} {(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">
<Avatar <Avatar
src={imageSrc} src={imageSrc}
alt={name} alt={name}
onError={handleImageError} sx={{ width: 200, height: 200, marginBottom: '16px' }}
sx={{ width: 100, height: 100, marginBottom: '16px' }} // Style the Avatar onClick={() => setImageOverlayVisible(true)}
onClick={handleAvatarClick}
/> />
</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"
@ -189,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"
@ -197,51 +134,62 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
margin="normal" margin="normal"
value={description} value={description}
onChange={(e) => setDescription(e.target.value)} onChange={(e) => setDescription(e.target.value)}
disabled={savingItem}
/> />
<TextField
label="Item Image Path" {loadingBoxes ? (
variant="outlined" <CircularProgress size={24} />
fullWidth ) : (
margin="normal" <select
value={imagePath} value={selectedBoxId}
onChange={(e) => setImagePath(e.target.value)} onChange={handleBoxChange}
/> disabled={savingItem}
<input >
type="file"
accept="image/*"
ref={fileInputRef}
style={{ display: 'none' }}
id="editItemImageUpload" // Unique ID
/>
<select value={selectedBoxId} onChange={handleBoxChange}>
<option value="">No box</option> <option value="">No box</option>
{boxes.map((box) => ( {boxes.map((box) => (
console.log('Box:', box.ID),
<option key={box.ID} value={box.ID}> <option key={box.ID} value={box.ID}>
{box.name} {box.name}
</option> </option>
))} ))}
</select> </select>
<br/> )}
<br/>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" component="label" htmlFor="editItemImageUpload"> <br />
Upload Image <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 <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 || '')}
// You can handle image preview here if needed
setImagePath(e.target.files[0].name);
}}
/> />
</Button> </Button>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleSave}> <Button
Save Changes sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={handleSave}
disabled={savingItem}
>
{savingItem ? <CircularProgress size={24} /> : 'Save Changes'}
</Button>
<Button
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
onClick={onClose}
disabled={savingItem}
>
Close
</Button> </Button>
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={onClose}>Close</Button>
</Container> </Container>
); );
} }

View File

@ -1,54 +1,111 @@
import React, { useEffect, useState, useCallback, useRef } from 'react'; import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import { import {
Container, Container,
List,
ListItem,
ListItemText,
TextField,
Button, Button,
IconButton, IconButton,
Typography, TextField,
TableContainer,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Box,
Tooltip,
Avatar, Avatar,
ListItemAvatar,
Dialog, Dialog,
DialogTitle, DialogTitle,
DialogContent, DialogContent,
DialogActions, 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 ItemDetails from './ItemDetails';
const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
<TableRow>
<TableCell>
<Avatar src={itemImages[item.ID] || '/images/default.jpg'} />
</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.description}</TableCell>
<TableCell>
<Box display="flex" justifyContent="space-between" width="100%">
<Tooltip title="Edit Item">
<IconButton onClick={() => onEdit(item)} size="large" sx={{ mr: 1 }}>
<EditIcon />
</IconButton>
</Tooltip>
<Tooltip title="Delete Item">
<IconButton onClick={() => onDelete(item.ID)} size="large" color="error">
<DeleteIcon />
</IconButton>
</Tooltip>
</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([]);
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 [searchQuery, setSearchQuery] = useState('');
const boxID = id;
const url = boxId === undefined ? `${process.env.REACT_APP_API_URL}/items` : `${process.env.REACT_APP_API_URL}/boxes/${boxId}/items`;
const { execute: fetchItems, loading: loadingItems, error: itemsError } = 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 debugLog = (message) => { const url = boxId ?
if (process.env.DEBUG_API) { `${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxId}/items` :
console.log(message); `${process.env.REACT_APP_API_URL}/api/v1/items`;
}
useEffect(() => {
const getItems = async () => {
try {
const response = await fetchItems(() =>
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
);
setItems(response.data);
// Fetch images for each item
response.data.forEach(item => {
api.items.getImage(token, item.ID)
.then(response => {
const reader = new FileReader();
reader.onload = () => {
setItemImages(prev => ({
...prev,
[item.ID]: reader.result
}));
}; };
debugLog("Box ID: " + boxID); reader.readAsDataURL(response.data);
})
.catch(() => {
setItemImages(prev => ({
...prev,
[item.ID]: '/default.jpg'
}));
});
});
} catch (err) {}
};
getItems();
}, [token, boxId]);
// const handleSelectItem = (item) => {
// setSelectedItem(item);
// };
const handleAddItem = () => { const handleAddItem = () => {
setOpenAddItemDialog(true); setOpenAddItemDialog(true);
}; };
@ -57,213 +114,124 @@ export default function Items({ token }) {
setOpenAddItemDialog(false); setOpenAddItemDialog(false);
setNewItemName(''); setNewItemName('');
setNewItemDescription(''); setNewItemDescription('');
// setNewItemImagePath('');
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ''; fileInputRef.current.value = '';
} }
}; };
const handleImageUpload = async (itemId, imageFile) => { const generateUniqueImageName = (imageName) => {
const formData = new FormData(); if (imageName.toLowerCase() === 'image.jpg') {
formData.append('image', imageFile); const randomString = Math.random().toString(36).substr(2, 9);
return `image_${randomString}.jpg`;
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/items/${itemId}/upload`, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
});
// console.log('Image uploaded successfully!');
return response.data.imagePath; // Indicate successful upload
} catch (error) {
console.error('Image upload failed:', error);
return null; // Indicate upload failure
} }
return imageName;
}; };
const handleSaveNewItem = async () => {
const handleSaveNewItem = useCallback(async () => {
try { try {
// 1. Create the item first const newItemResponse = await createItem(() =>
const newItemResponse = await axios.post(`${process.env.REACT_APP_API_URL}/items`, { api.items.create(token, {
name: newItemName, name: newItemName,
description: newItemDescription, description: newItemDescription,
box_id: parseInt(boxId, 10) box_id: parseInt(boxId, 10)
}, { })
headers: { );
Authorization: `Bearer ${token}`
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)
);
if (newItemResponse.data.id) {
try {
const imageResponse = await api.items.getImage(token, newItemResponse.data.id);
const reader = new FileReader();
reader.onload = () => {
setItemImages(prev => ({
...prev,
[newItemResponse.data.id]: reader.result
}));
};
reader.readAsDataURL(imageResponse.data);
} catch (err) {
setItemImages(prev => ({
...prev,
[newItemResponse.data.id]: '/default.jpg'
}));
} }
});
//console.log('New item created:', newItemResponse.status);
// 2. If item creation is successful, upload the image
if (newItemResponse.status === 200 && fileInputRef.current.files[0]) {
const newItemId = newItemResponse.data.id;
const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0]);
if (uploadedImagePath) {
// console.log("Image path to save:", uploadedImagePath);
// You might want to update your item in the backend with the image path
// For example:
// await axios.put(...);
} else {
// Handle image upload failure
console.error('Failed to upload image for the new item.');
} }
} }
handleCloseAddItemDialog(); handleCloseAddItemDialog();
fetchItems();
} catch (error) {
console.error('Error adding item:', error);
}
};
const response = await fetchItems(() =>
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
);
//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}/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(() => {
axios.get( url, {
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setItems(response.data); setItems(response.data);
} catch (err) {}
}, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems]);
// Fetch images for each item const handleDeleteItem = useCallback(async (itemId) => {
response.data.forEach(item => { try {
getImageSrc(item.ID).then(imageDataUrl => { await deleteItem(() => api.items.delete(token, itemId));
setItemImages(prevItemImages => ({ setItems(prev => prev.filter(item => item.ID !== itemId));
...prevItemImages, } catch (err) {}
[item.ID]: imageDataUrl }, [token, deleteItem]);
}));
});
});
});
}, [token, getImageSrc, url]);
// lint says I don't need boxId here
useEffect(() => { const handleEditItem = useCallback((item) => {
fetchItems();
}, [boxId, token, fetchItems]);
// const handleAddItem = () => {
// const formData = new FormData();
// formData.append('name', newItemName);
// formData.append('description', newItemDescription);
// formData.append('box_id', parseInt(boxId, 10));
// // Append image only if a new one is selected
// if (fileInputRef.current.files[0]) {
// formData.append('image', fileInputRef.current.files[0]);
// }
// axios.post(`${process.env.REACT_APP_API_URL}/items`, formData, {
// headers: {
// Authorization: `Bearer ${token}`,
// 'Content-Type': 'multipart/form-data' // Important for file uploads
// }
// }).then(() => {
// setNewItemName('');
// setNewItemDescription('');
// setNewItemImagePath('');
// // Clear the file input
// if (fileInputRef.current) {
// fileInputRef.current.value = '';
// }
// fetchItems();
// });
// };
const handleDeleteItem = (itemId) => {
axios.delete(`${process.env.REACT_APP_API_URL}/items/${itemId}`, {
headers: { Authorization: `Bearer ${token}` }
}).then(() => {
fetchItems();
});
};
const handleEditItem = (item) => {
setEditingItem(item); setEditingItem(item);
}, []);
const handleSaveEdit = async () => {
setEditingItem(null);
const response = await fetchItems(() =>
api.items.getAll(token, boxId)
);
setItems(response.data);
}; };
const handleSaveEdit = () => { const filteredItems = useMemo(() =>
setEditingItem(null); items.filter(item =>
fetchItems(); item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
}; item.description.toLowerCase().includes(searchQuery.toLowerCase())
),
[items, searchQuery]
);
return ( return (
<Container> <Container>
<h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : boxName}</h2> {(itemsError || createError || deleteError || uploadError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{itemsError?.message || createError?.message || deleteError?.message || uploadError?.message}
</Alert>
)}
<input <TextField
type="file" label="Search"
accept="image/*" variant="outlined"
ref={fileInputRef} fullWidth
style={{ display: 'none' }} margin="normal"
id="newItemImageUpload" // Unique ID value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/> />
<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>
@ -287,59 +255,57 @@ export default function Items({ token }) {
type="file" type="file"
accept="image/*" accept="image/*"
ref={fileInputRef} ref={fileInputRef}
style={{ display: 'block', margin: '10px 0' }} // Style as needed style={{ display: 'block', margin: '10px 0' }}
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}
/> />
) : (
<List>
{items.map((item) => (
<ListItem key={item.ID} secondaryAction={
<>
<IconButton edge="end" onClick={() => handleEditItem(item)}>
<EditIcon />
</IconButton>
<IconButton edge="end" onClick={() => handleDeleteItem(item.ID)}>
<DeleteIcon />
</IconButton>
</>
}>
<ListItemAvatar>
<Avatar
src={itemImages[item.ID]}
alt={item.name}
onError={handleImageError}
/>
</ListItemAvatar>
<ListItemText
primary={item.name}
secondary={
<>
<Typography variant="body2">{item.description}</Typography>
{item.image_path && (
<Typography variant="caption">Image: {item.image_path}</Typography>
)} )}
</>
} {loadingItems ? (
<CircularProgress />
) : (
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell style={{ width: '40px' }}>Image</TableCell>
<TableCell style={{ width: '100px' }}>Name</TableCell>
<TableCell>Description</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{filteredItems.map((item) => (
<Item
key={item.ID}
item={item}
itemImages={itemImages}
onDelete={handleDeleteItem}
onEdit={handleEditItem}
/> />
</ListItem>
))} ))}
</List> </TableBody>
</Table>
</TableContainer>
)} )}
</Container> </Container>
); );

View File

@ -1,27 +1,26 @@
// src/components/Login.js // src/components/Login.js
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Button, TextField, Container, Typography, Alert } from '@mui/material'; import { Button, TextField, Container, Typography, Alert, CircularProgress } from '@mui/material';
import axios from 'axios'; import { useNavigate } from 'react-router-dom';
import { useNavigate } from 'react-router-dom'; // Import useNavigate
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
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); // State for login error const navigate = useNavigate();
const navigate = useNavigate(); // Initialize useNavigate const { execute, loading, error } = useApiCall();
const handleLogin = async (e) => { const handleLogin = async (e) => {
e.preventDefault(); e.preventDefault();
setLoginError(false); // Reset error state on each login attempt
try { try {
// eslint-disable-next-line no-template-curly-in-string const response = await execute(() => api.login({ username, password }));
const response = await axios.post(`${process.env.REACT_APP_API_URL}/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); // Set error state if login fails console.error('Login attempt failed');
} }
}; };
@ -29,9 +28,10 @@ export default function Login({ setToken }) {
<Container maxWidth="xs"> <Container maxWidth="xs">
<Typography variant="h4" gutterBottom>Login</Typography> <Typography variant="h4" gutterBottom>Login</Typography>
{/* Display error message if loginError is true */} {error && (
{loginError && ( <Alert severity="error">
<Alert severity="error">Login Failed</Alert> {error.status === 401 ? 'Invalid username or password' : error.message}
</Alert>
)} )}
<form onSubmit={handleLogin}> <form onSubmit={handleLogin}>
@ -52,8 +52,15 @@ export default function Login({ setToken }) {
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" type="submit" fullWidth> <Button
Login sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
variant="contained"
color="primary"
type="submit"
fullWidth
disabled={loading}
>
{loading ? <CircularProgress size={24} /> : 'Login'}
</Button> </Button>
</form> </form>
</Container> </Container>

View File

@ -33,9 +33,10 @@ export default function Navbar() {
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}> <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Boxes Boxes
</Typography> </Typography>
<Button color="inherit" component={Link} to="/login">Login</Button> <Button color="inherit" component={Link} to="/api/v1/login">Login</Button>
<Button color="inherit" component={Link} to="/boxes">Boxes</Button> <Button color="inherit" component={Link} to="/api/v1/boxes">Boxes</Button>
<Button color="inherit" component={Link} to="/items">Items</Button> <Button color="inherit" component={Link} to="/api/v1/items">Items</Button>
<Button color="inherit" component={Link} to="/api/v1/admin">Admin</Button>
<Button color="inherit" onClick={handleLogout}>Logout</Button> <Button color="inherit" onClick={handleLogout}>Logout</Button>
</Toolbar> </Toolbar>
</AppBar> </AppBar>

View File

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

View File

@ -4,6 +4,14 @@ import './index.css';
import App from './App'; import App from './App';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
const path = window.location.pathname;
if (path !== '/' && !path.startsWith('/api/v1/')) {
window.history.replaceState(null, '', '/');
}
// Log the environment variables
console.log('REACT_APP_API_URL:', process.env.REACT_APP_API_URL);
const root = ReactDOM.createRoot(document.getElementById('root')); const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <React.StrictMode>

72
src/services/api.js Normal file
View File

@ -0,0 +1,72 @@
// src/services/api.js
import axios from 'axios';
const createApiClient = () => {
const client = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
const authHeader = (token) => ({ Authorization: `Bearer ${token}` });
return {
// Auth
login: (credentials) =>
client.post('/api/v1/login', credentials),
// Items
items: {
getAll: (token) =>
client.get('/api/v1/items', { headers: authHeader(token) }),
getOne: (token, id) =>
client.get(`/api/v1/items/${id}`, { headers: authHeader(token) }),
create: (token, itemData) =>
client.post('/api/v1/items', itemData, { headers: authHeader(token) }),
update: (token, id, itemData) =>
client.put(`/api/v1/items/${id}`, itemData, { headers: authHeader(token) }),
delete: (token, id) =>
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' }
}),
getImage: (token, id) =>
client.get(`/api/v1/items/${id}/image`, {
headers: authHeader(token),
responseType: 'blob'
}),
getByBox: (token, boxId) =>
client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }),
},
// Boxes
boxes: {
getAll: (token) =>
client.get('/api/v1/boxes', { headers: authHeader(token) }),
create: (token, boxData) =>
client.post('/api/v1/boxes', boxData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }),
},
// Admin
admin: {
getUsers: (token) =>
client.get('/api/v1/admin/user', { headers: authHeader(token) }),
createUser: (token, userData) =>
client.post('/api/v1/admin/user', userData, { headers: authHeader(token) }),
deleteUser: (token, id) =>
client.delete(`/api/v1/admin/user/${id}`, { headers: authHeader(token) }),
backupDb: (token) =>
client.get('/api/v1/admin/db', {
headers: authHeader(token),
responseType: 'blob'
}),
restoreDb: (token, formData) =>
client.post('/api/v1/admin/db', formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
}
};
};
export const api = createApiClient();

View File

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

18
test.bash Normal file
View File

@ -0,0 +1,18 @@
#!/bin/bash
# Set the username and password
USERNAME="boxuser"
PASSWORD="boxuser"
EMAIL="boxuser@r8z.us"
# Set the database file and table name
DB_FILE="../boxes-api/data/boxes.db"
TABLE_NAME="users"
# Generate the bcrypt encrypted password using htpasswd
ENCRYPTED_PASSWORD=$(htpasswd -bnBC 10 "" "$PASSWORD" | tr -d ':\n')
# Insert the username and encrypted password into the database
sqlite3 "$DB_FILE" "INSERT INTO $TABLE_NAME (username, password, email) VALUES ('$USERNAME', '$ENCRYPTED_PASSWORD', '$EMAIL')"
echo "Password encrypted and stored in the database."